PHP & OOP: Constructors and destructors

This entry is part 8 of 11 in the series PHP & OOP

As an object-orientted programming language, PHP 5 allows developers to declare constructor methods for classes.

Classes which have a constructor method will call this method on each newly-created object.

So in a way, constructor is used to automate the task of creating a new object.

The destructor method will be called when there are no references to a particular object, or during the shutdown sequence.

In the code below, the destructor will be called when the running of php script is completed.


class PopStar
    public $person;
    public $salary;
    public $album;

    function __construct($pop, $sal, $alb )
        echo "Construct function automatically called";
        echo "<br>";
        $this->person = $pop;
        $this->salary = $sal;
        $this->album = $alb;

    function __destruct(){
        echo "Destruct function automatically called";
        echo "<br>";

    public function getSalary()
        echo $this->salary;

$star = new PopStar("Madonna", 10000, "Crazy For You");
echo "The pop star salary is:";
echo "<br>";
echo "<br>";


The output from running the above script is:


Series Navigation<< PHP & OOP: Methods of a class
PHP & OOP: Visibility >>

Leave a comment

Leave a Reply