Lets revisit that definition in more simple terms. A constructor is a special function – this means that a constructor is a function; but its special. But, why is it special? It’s special because it is automatically executed or called when an object of a class is created.
We need a Constructor?
It is needed as it provides an opportunity for doing necessary setup operations like initializing class variables, opening database connections or socket connections, etc. In simple terms, it is needed to setup the object before it can be used.
Let’s look at a real example:
We need a Constructor?
It is needed as it provides an opportunity for doing necessary setup operations like initializing class variables, opening database connections or socket connections, etc. In simple terms, it is needed to setup the object before it can be used.
class Customer { public function __construct() { //code } }
class Customer { private $first_name; private $last_name; private $outstanding_amount; public function __construct() { $first_name = ""; $last_name = ""; $outstanding_amount = 0; } public function setData($first_name, $last_name, $outstanding_amount) { $this->first_name = $first_name; $this->last_name = $last_name; $this->outstanding_amount = $outstanding_amount; } public function printData() { echo "Name : " . $first_name . " " . $this->last_name . "\n"; echo "Outstanding Amount : " . $this->outstanding_amount . "\n"; } } $c1 = new Customer(); $c1->setData("Sunil","Bhatia",0);