If the user wants to access any member function of a class then he or she must create the
The c
No need to call it by an object. Simply constructor is a function which called when
Constructor declares by two ways.
- Define function name same as class name. (This is old way to declare constructor. It is use in PHP 5.3.3 version)
- Define function by __construct keyword.
Only one constructor creates in one class. It is used to run
Like Database Connection. The constructor
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php class Computer { var $cpu; var $ram; var $hdd; function __construct($c, $r, $h) // Constructor { $this->cpu = $c; $this->ram = $r; $this->hdd = $h; } function describe() { echo "Hello, I am a Computer. My CPU is $this->cpu GHz, with $this->ram GB RAM and $this->hdd GB Hard Disk"; } } $dell = new Computer(2.4, 4, 512); $dell->describe(); ?> |
Output:
1 | Hello, I am a Computer. My CPU is 2.4GHz, with 4 GB RAM and 512 GB Hard Disk. |
Explanation
In above example $dell is an object of Computer class when its created constructor automatically called and CPU, RAM and Hard disk value passed by parameter.
Then when called describe() function its return the whole value
Destructor
Destructor also called automatically when object an of any class but it’s run when The constructor creates.
It the for free up memory. Using this after complete a task unset all variable and
Destructor defines by __destruct keyword.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?php class Animal { public $name = "No-name animal"; public function __destruct() { echo "<br>I'm dead now :("; } public function __construct($name) { echo "I'm alive!"; $this->name = $name; } } $animal = new Animal("Bob"); echo "Name of the animal: " . $animal->name; ?> |
Output
1 2 | I'm alive! Name of the animal: Bob I’m dead now |