PHP Constructors Destructors

by Vincy. Last modified on July 9th, 2022.

While working with the PHP object model, we need to set the properties of that object, before using it as a reference to access class member functions. For such initial settings, object-oriented concepts are there, that are commonly used in many object-oriented languages.

Constructors and destructors are such object-oriented concepts supported by PHP. Constructors are used for initializing object properties before using them, and destructors are used for destroying object references.

PHP Constructors Destructors Syntax

In PHP, Constructors and destructors are defined for a class by using PHP magic functions __construct, __destruct, respectively. And their syntax is shown below.

<?php
class <class-name> {

    function __construct()
    {
        // initializing object properties
    }

    function __destruct()
    {
        // clearing object reference
    }
}
?>

Like other languages, PHP constructors can accept more arguments, whereas, destructors will have nothing as their argument, and it is simply void. Because, with destructors, we are just destroying the current object reference, which doesn’t require any parameters.

Backward Compatibility

In older PHP versions with the older object model, the constructors are defined with the name of the classes, as we have familiar with other object-oriented languages. For example,

<?php
class <class-name> {
    function <class-name>(){
        //initializing object properties
    }
}
?>

Still, PHP supports this form of constructors to provide backward compatibility for supporting PHP projects developed in older versions of PHP.

So, while creating objects for a class, PHP will search for the magic method __construct(). If not found and there is a function defined with the name of the class, then, PHP will treat it as the constructor and will call it automatically, for initializing object properties.

Note:

As of PHP version 5.3.3, if a class is a namespaced class, then, the function with the name of that class will not be treated as the constructor, rather, it will be considered a normal function.

Inheriting Constructors

By using another object-oriented concept, inheritance, supported by PHP, we are going to inherit constructors from parent class to child class derived from it.

So, a derived class need not have any constructor separately, if the child is not required any special object initialization of its own. In such a scenario, PHP allows inheriting the parent class constructor to its child also. For example,

<?php

class Toys
{

    public $name;

    public $price;

    function __construct($name, $price)
    {
        $this->name = $name;
        $this->price = $price;
        echo "Properties initialized by parent constructor";
    }

    function __destruct()
    {
        echo "Object reference is cleared";
    }

    function get_toys_info()
    {
        $toys["name"] = $this->name;
        $toys["price"] = $this->price;
        return $toys;
    }
}

class Mechanical_Toys extends Toys
{
}
$objMechanicalToys = new Mechanical_Toys("Battery Car", 500);
$toys_info = $objMechanicalToys->get_toys_info();
print "<PRE>";
print_r($toys_info);
print "</PRE>";
?>

In the above program, we have created a superclass Toys, having its own constructor, destructor and a function get_toys_info to return to details. And then, we derived a child class Mechanical_Toys from Toys class.

We can see with the above code that this child class have no constructor, destructor, and no other members.

After completing class definitions, let us create an object of the child class. Even though it doesn’t have any members, it can inherit the members of the parent class, if we create an object with an appropriate number of parameters, as its constructor has.

Since we are creating a child class object with two parameters, PHP will search for the two-argument constructor to be called, automatically. And, we have such constructor with parent class, which will be inherited, and so, child object properties will be initialized. For that PHP $this variable is used for referring to those properties in object perspective.

Note:

When the child class has its own constructor and destructor, then, they will be invoked with higher preference, while creating child class objects. Let us see about it in detail in an upcoming paragraph.

Overriding PHP Constructors Destructors

By overriding parent class constructors and destructors by that of the child class, we can handle some special initialization, which is specifically used for child class objects. For that, we should add another set of __construct() and __destruct magic functions to the child class, as its own. So, the code will be as follows.

<?php

class Mechanical_Toys extends Toys
{

    public $category;

    function __construct($name, $price)
    {
        $this->name = $name;
        $this->price = $price;
        $this->category = "Mechanical Toys";
        echo "Properties initialized by child constructor";
    }

    function __destruct()
    {
        echo "Object reference is cleared by child constructor";
    }
}
?>

After that, these newly added child class constructors and destructors will be invoked on child instance creation and exit, respectively. In this child class constructor, one more object property, that is, the toys category is initialized.

Note:

  • Instead of assigning name and price properties once again for the child class, we can invoke the parent constructor, like, parent::__construct. So, the code will be,
    <?php
    
    function __construct($name, $price)
    {
        parent::__construct($name, $price);
        $this->category = "Mechanical Toys";
        echo "Properties initialized by child constructor";
    }
    ?>
    

Download PHP Constructor Destructor Source Code

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page