A constructor enables the initialization of an object’s properties when the object is created.
When you define a __construct()
function, PHP automatically invokes this function when a new object is instantiated from the class.
Note that the constructor function begins with two underscores (__
).
In the example below, using a constructor eliminates the need to call the set_name()
method separately, reducing the amount of code.
<?php class Fruit { public $name; public $color; function __construct($name) { $this->name = $name; } function get_name() { return $this->name; } } $apple = new Fruit(“Apple”); echo $apple->get_name(); ?> |
Another example:
<?php class Fruit { public $name; public $color; function __construct($name, $color) { $this->name = $name; $this->color = $color; } function get_name() { return $this->name; } function get_color() { return $this->color; } } $apple = new Fruit(“Apple”, “red”); echo $apple->get_name(); echo “<br>”; echo $apple->get_color(); ?> |