Just like JavaScript constructor, PHP constructor initializes object’s properties when you create an object.
To add a constructor, you need to add a __construct() function in the class. So, when you create an object using that class, PHP will automatically call the __construct() function.
One of the advantage of adding a constructor is that you don’t need to add set_name() method and call it.
Syntax
__construct (optional values)
You can pass multiple values with different types of variables, though it’s optional. You can skip passing any values. It doesn’t have any return values.
PHP __construct() function example
make = $make;
$this->model = $model;
}
function get_name() {
return $this->make;
}
function get_model() {
return $this->model;
}
}
$car1 = new Car("Honda","Accord");
echo "The model for " . $car1->get_name() . " is " . $car1->get_model();
//The model for Honda is Accord
?>
What happens when there’s a child class?
When you define a child class constructor, the parent constructors are NOT called implicitly.
If you want to call the parent class constructor then use this inside child constuctor:
...
parent::__construct()
...
If the child class doesn’t have a constructor defined then it may be inherited from the parent class.
PHP __construct() function example with inheritance
Here’s a really good example from PHP official docs to understand the constructor with inheritance.
class constructor examples functions object-oriented objects OOP