tags:

views:

54

answers:

2

Hello, I have the following two classes.

Settings:


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

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

$page = new PageManager();

I thought that would work fine, but it only runs PageManager's construct. I'm guessing it's because I override the Setting's function. Is there some way I can call the original function?

+7  A: 

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

Iznogood
it's better to call parent constructor before all instructions in child constructor, therefore we are sure that parent object is ready to use.
Tomasz Kowalczyk
@Tomasz Kowalczyk Is it? Well I changed my answer to reflect this so thanks! :)
Iznogood
@Thomasz That entirely depends on what the parent and the child constructors are supposed to do. It's not *always* better.
deceze
@Iznogood: if it is good, please vote up ;]
Tomasz Kowalczyk
@deceze - yes, you are right, but in most cases calling it first is better option, especially if we cannot see the base class implementation.
Tomasz Kowalczyk
@Tomasz Kowalczyk Voted up :)
Iznogood
A: 

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