A Constructor allows you to initialize an object's properties upon creation of the object.
If you create a __construct() function, PHP will automatically call this function whenever you create an object from a class using the new keyword.
__construct() FunctionNotice that the constructor function starts with two underscores (__). This is known as a "magic method" in PHP.
Using a constructor drastically reduces the amount of code you have to write. Instead of manually calling setter functions to configure your object, you can pass arguments directly when you instantiate it!
<?php
class Car {
public $brand;
public $color;
// The constructor automatically takes the arguments and assigns them
function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
}
function get_details() {
return "The car is a " . $this->color . " " . $this->brand . ".";
}
}
// We pass the values directly into the parentheses!
$myCar = new Car("Volvo", "red");
echo $myCar->get_details();
?>
Before constructors, if you wanted to build an object with 5 properties, you had to call 5 separate setter functions. With a constructor, you can configure the entire object on the exact same line of code that creates it.
This guarantees that an object is never created in a "half-finished" or incomplete state, ensuring reliability across your PHP application!