All method in php which start with double underscore they are called magic method in php . first we learn __construct() method . here we will learn about __construct() method like Syntax of __construct() method , use of construct method , how to initialized a class properties using construct method .
Syntax of __construct() method .
<?php class dbmodel{ public function __construct(){ /* write code here */ } } ?>
Construct method execute automatically when the object of class will initialize . Lets see and understand with a example .
<?php class dbmodel{ public function __construct(){ echo "you are inside in construct method <br />"; } public function insert(){ echo "you are inside in insert method"; } } $db_obj = new dbmodel; $db_obj->insert(); ?>
Here in this example we define a "dbmodel" class and inside this class create a construct and insert method . So we prepare all code . Now we create object of "dbmodel" class and access the insert method . when call the insert method , then construct method is made automatically with the insert method . and get the response like below .
Output :
you are inside in construct method you are inside in insert method
lets see the next example and understand . we can initialize the class properties using __construct() method .
<?php class dbmodel{ public $welcome = ''; public function __construct($welcome){ $this->welcome = $welcome; echo $this->welcome."<br />"; } public function insert(){ echo "you are inside in insert method"; } } $db_obj = new dbmodel("hello , welcome in jswebsolutions ."); $db_obj->insert(); ?>