The __construct() Function
A constructor is a special method named __construct(). PHP runs it automatically every time you create a new object from the class with the new keyword.
It can take arguments, which you supply at the moment the object is created, as in $apple = new Fruit("Apple", "Red");. That way, each object is set up with its own values right away and you write less code.
Watch the name: it begins with two underscores (__).
The next example relies on __construct() to fill in the properties. Since PHP calls it for us, there is no need for a separate call to a set_details() method, and the code gets shorter:
Constructor Example
Set an object's properties at creation time with __construct():
Output: PHP script
<?php
class Fruit {
public $name;
public $color;
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function get_details() {
echo "Name: " . $this->name . ". Color: " . $this->color .".<br>";
}
}
$apple = new Fruit('Apple', 'Red');
$apple->get_details();
$banana = new Fruit('Banana', 'Yellow');
$banana->get_details();
?>
Example Explained
The Fruit class declares two properties, $name and $color.
Whenever a new Fruit object appears, __construct() stores the values it received in those properties.
The job of get_details() is to print the fruit's name and color.
The line that creates $apple passes the values "Apple" and "Red" to the constructor, and the line that creates $banana does the same with "Banana" and "Yellow".
Finally, calling get_details() on each of the two objects displays that fruit's details.