PHP Tutorial Tutorials - PHP Constructor and Destructor

PHP Constructor and Destructor

PHP Constructor and Destructor

  • In PHP, the magic method __construct() (known as constructor) is called automatically on each newly-created object.
    (In PHP 3 and 4 constructors are methods that share the same name as the class)
  • Similarly, the magic method __destruct() (known as destructor) is executed automatically when the object is destroyed.
  • A destructor function cleans up any resources allocated to an object once the object is destroyed.

Constructor

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
  • The __CLASS__ is a magic constant which is the class name includes the namespace it was declared in.
  • The __construct() method should always be public

Constructor with arguments

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
?>

Destructor

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

Date:2019-10-09 00:35:47 From:www.Lautturi.com author:Lautturi