Constructors are the very basic building blocks that define the future object and its nature. You can say that the Constructors are the blueprints for object creation providing values for member functions and member variables.
If you create a __construct()
function, PHP will automatically call this function when you create an object from a class.
<?php class Fruit { public $name; public $color; function __construct($name) { echo $this->name = $name."<br/>"; } function get_name() { return $this->name; } } $apple = new Fruit("Apple"); echo $apple->get_name(); ?>
<?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(); ?>