PHP Constructor
The constructor is a special type of method in PHP class that is automatically executed when an object of the class is created. Its function is to initialize the properties of the object or to perform any other setup tasks required when an object is created.
Syntax
class ClassName {
// Properties
public $prop1;
public $prop2;
// Constructor
public function __construct($val1, $val2) {
$this->prop1 = $val1;
$this->prop2 = $val2;
}
}
Example
class Rectangle {
public $length;
public $width;
public $area;
public function __construct($length, $width) {
$this->length = $length;
$this->width = $width;
$this->area = $this->length * $this->width;
}
}
$rectangle = new Rectangle(5, 10);
echo "Area of rectangle is " . $rectangle->area;
Output
Area of rectangle is 50
Explanation
In the above example, we have defined a class Rectangle
with three properties (length
, width
, and area
). We have also defined a constructor for the class which takes two arguments ($length
and $width
) and initializes the properties of the object.
When we create an object of the Rectangle
class using the new
keyword and passing the values 5
and 10
for $length
and $width
respectively, the constructor is automatically executed which sets the values for the properties and calculates the area
based on the length and width.
Finally, we have printed the area
of the rectangle object using the echo
statement.
Use
Constructors are used to initialize the properties of an object of a class when it is created. They are also used to perform any other setup tasks required when an object is created.
Important Points
- A constructor must have the same name as the class and cannot return a value.
- If a class does not have a constructor defined then a default constructor with no arguments is created by PHP.
- Multiple constructors with different arguments are not possible in PHP but we can use default values to simulate overloading.
Summary
In PHP, a constructor is a special type of method that is automatically executed when an object of a class is created. Its purpose is to initialize the properties of the object or to perform any other setup tasks required when an object is created. Constructors are important for creating objects and are used extensively in object-oriented programming in PHP.