PHP OOP - Constructor Method
PHP - The __construct() Function
The PHP
__construct() function is a special method within a class that is automatically
called each time a new object is created from a class (with the
new keyword).
The
__construct() function accept arguments, which are passed upon object
creation (e.g., $apple = new Fruit("Apple", "Red");). This allows for dynamic
initialization (reduces code).
Notice that the __construct() function starts with two underscores (__)!
Look at the example below: Here we use the
__construct() function (that is automatically called each time a
new object is created from a class), which saves us from
calling the set_details() method (which reduces the amount of code):
Example
<?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();
?>
Try it Yourself »
Example Explained
- The Fruit class is defined with two properties: $name and $color.
- The __construct() method initializes the properties when a new object of the Fruit class is created, using the provided values.
- The get_details() method is defined to print out the fruit's name and color.
- A new object $apple is created from the Fruit class, and values ("Apple", "Red") are passed to the constructor.
- A new object $banana is created from the Fruit class, and values ("Banana", "Yellow") are passed to the constructor.
- The get_details() method is called on the $apple and $banana objects to display the details of the fruit.