PHP5 Constructor: Let Be Expert

It is a day to learn and become master about PHP5 constructor concept after learning the class basics, class properties and class methods. I will continue our Product class, so it will be easy to mastering OOP for the regular visitors of TutorialChip.

What is Constructor Method

A constructor method is invoked when an object is created. You can use it to set things up, ensuring that essential properties are set, and any necessary preliminary work is completed. You should name your constructor method __construct(). Constructor method name begins with two underscore characters.

A constructor is a special function of a class that is automatically executed whenever an object of a class gets instantiated.

__construct Example

/**
* Class Tutorial
*/

class Product {

	/**
	* Class Properties
	*/

	public $productTitle;
	public $productName;
	public $productPrice;

	/**
	* Class Methods
	*/

	/**
	* Class Constructor
	*/

	public function __construct( $productTitle = "Product Title", $productName = "Product Name", $productPrice = 0 ) {

		$this->productTitle = $productTitle;
		$this->productName = $productName;
		$this->productPrice = $productPrice;

	}

	/**
	* Get Product
	*/

	public function getProduct() {
		$temp = "Title: " . $this->productTitle . " <br />";
		$temp .= "Name: " . $this->productName . " <br />";
		$temp .= "Price: " . $this->productPrice . " <br />";
		return $temp;
	}

}

/**
* Class Object 1
*/

$product1 = new Product( "Smart Phone", "iPhone", "$399" );

/**
* Get Object 1 Properties
*/

$product = $product1->getProduct();
echo $product;
echo "<hr />";

/**
* Class Object 2
*/

$product2 = new Product( "Laptop", "HP Pavilion", "$799" );

/**
* Get Object 2 Properties
*/

$product2 = $product2->getProduct();
echo $product2;
echo "<hr />";

Output:

Output of above code will be,

Title: Smart Phone
Name: iPhone
Price: $399

Title: Laptop
Name: HP Pavilion
Price: $799

Summary

  • A constructor method is invoked when an object is created.
  • Any arguments supplied are passed to the constructor.
  • The constructor method uses the pseudo-variable $this to assign values to each of the object’s properties.

I hope you have learned the concept of PHP5 constructor, and don’t forget to subscribe to learn more about php and other resources.

One thought

Comments are closed.