How to create the class constructor in PHP
Overview
In OOP, when a constructor is declared, it initializes the properties of an object.
The __construct function
In PHP, we have the __construct function for such purposes.
Note: We use the double underscore
__beforeconstruct.
Once we have the __construct() function in a class, the subsequent object of that class will initiate the variables and the functions inside it. Therefore, we don’t have to manually create/initialize them.
Code
For instance, in the provided example, we don't have to call the specific functions, set_brand() and set_name() to initialize the brand and name variables. This is because it's been done by the __construct() function that saves up our code space and reduces the manual efforts/steps we have to perform for such purposes.
<?phpclass Car {public $brand;public $name;function __construct($brand, $name) {$this->brand = $brand;$this->name = $name;}function get_brand() {return $this->brand;}function get_name() {return $this->name;}}$car1 = new Car("Honda", "Civic");echo $car1->get_brand();echo " ";echo $car1->get_name();?>
Explanation
- Lines 1-18: We create a class named
Carwith abrandand aname. Then, we create the__constructfunction and pass thebrandandnameas its parameters. This function initializes thebrandandnamewith the input that the user provides when it creates a class object. Furthermore, we create aget_brand()andget_name()function to return thebrandandnamethat is assigned to the class object. - Lines 20-23: We create a
Carobjectcar1and pass it thebrandandnamein the braces. After this, we simply print thebrandandnamethrough the get functions.