__construct()
(known as constructor) is called automatically on each newly-created object.__destruct()
(known as destructor) is executed automatically when the object is destroyed.When a new object is created, one of the first things that happens is that the constructor is called.
The code included inside a constructor should set the newly created object to its initial, stable, safe state.
<?php class House { public $color = "red"; function __construct() { print "In class ".__CLASS__." constructor\n"; } public function changeColor($newcolor) { $this -> color = $newcolor; } } $house = new House(); echo $house -> color; //red ?>
Outputs:
In class House constructor red
__CLASS__
is a magic constant which is the class name includes the namespace it was declared in.__construct()
method should always be public
you can initialize the data when you create the object by sending parameters.
<?php class House { public $color = "red"; function __construct($color) { print "In class ".__CLASS__." constructor\n"; $this-color = $color; } public function changeColor($newcolor) { $this -> color = $newcolor; } } $house = new House("blue"); echo $house -> color; // blue ?>
In PHP,it will automatically clean up all allocated resources when the script ends (or exit
,die
).So the destructor is called automatically when the object is destroyed.
<?php class House { public $color = "red"; function __destruct(){ echo "In destructor\n"; } public function changeColor($newcolor) { $this -> color = $newcolor; } } $house = new House(); echo $house -> color; //red echo "the end of the script\n" ?>
Outputs:
red the end of the script In destructor