Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling parent's constructor in PHP

Tags:

oop

php

subclass

I have the following two classes.

class Settings
{
    function __CONSTRUCT()
    {
        echo "Settings Construct";
    }
}

class PageManager extends Settings
{
    function __CONSTRUCT()
    {
        echo "PageManager Construct";
    }
}

$page = new PageManager();

I thought that would work fine, but it only runs PageManager's constructor. I'm assuming it's because I override the Setting's constructor. Is there some way I can call the parent's constructor as well?

like image 331
Ryan Pendleton Avatar asked Sep 10 '10 00:09

Ryan Pendleton


People also ask

How can we call a parent class constructor?

For calling the constructor of a parent class we can use the super keyword. The super() method from the constructor method is used for the invocation of the constructor method of the parent class to get access to the parent's properties and methods.

Does PHP automatically call parent constructor?

The fact that PHP always calls the "nearest" constructor, that is if there is no child constructor it will call the parent constructor and not the grandparent constructor, means that we need to call the parent constructor ourselves. We can do this by using the special function call parent::__construct().

How do you call a constructor in PHP?

PHP - The __construct Function A constructor allows you to initialize an object's properties upon creation of the object. If you create a __construct() function, PHP will automatically call this function when you create an object from a class. Notice that the construct function starts with two underscores (__)!

How can you call a constructor for a parent class in Wordpress?

To call the constructor of the parent class from the constructor of the child class, you use the parent::__construct(arguments) syntax. The syntax for calling the parent constructor is the same as a regular method.


1 Answers

Just call it using parent::

    /* Settings */
class Settings{
 function __CONSTRUCT(){
  echo "Settings Construct";
 }
}

/* PageManager */
class PageManager extends Settings{
 function __CONSTRUCT(){
    parent::__CONSTRUCT();
    echo "PageManager Construct";
 }
}

Have a look at the manual(Constructors and Destructors)!

like image 158
Iznogood Avatar answered Sep 27 '22 23:09

Iznogood