11

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?

0

2 Answers 2

17

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)!

5
  • 7
    it's better to call parent constructor before all instructions in child constructor, therefore we are sure that parent object is ready to use. Sep 10, 2010 at 1:02
  • @Tomasz Kowalczyk Is it? Well I changed my answer to reflect this so thanks! :)
    – Iznogood
    Sep 10, 2010 at 1:08
  • @Thomasz That entirely depends on what the parent and the child constructors are supposed to do. It's not always better.
    – deceze
    Sep 10, 2010 at 1:11
  • @deceze - yes, you are right, but in most cases calling it first is better option, especially if we cannot see the base class implementation. Sep 10, 2010 at 1:15
  • @Tomasz Kowalczyk Voted up :)
    – Iznogood
    Sep 10, 2010 at 1:49
0

In addition: you should know that this behaviour of PHP is not unique to the __construct() function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.