Constructors

Similar to JavaScript Constructors, the PHP Constructors are used to declare methods for basic classes.

A constructor is called or evoked everytime a new class object has been initialized. A parent class does not need to call the constructor explicitly, if the child class defines it. From child class a parent:: _construct() is required. Sometimes, a child class does not define a constructor in case it is inherited from the parent class.

Syntax for a class constructor

<?php
    // creating class
    class className
    {
        function _construct()
        {
            //code here...
        }
    }
    
    // initializing obect
    $object = new className;
?>

Subclass constructors (extends)

Objects can also be created from sub-classes that are part of some parent class. To be able to do that a sub-class has to be already created. The creation of a sub-class is done by using the keyword extends. The example below shows how that can be done:

Examples with class constructors and constructors extends

Destructors

A destructor serves to "destruct" a reference to a particular object; or in other word it clears the code from the initialized object and it's ties to the constructor.

 

›› go to examples ››