开发者

Calling parent's constructor in PHP

开发者 https://www.devze.com 2023-01-15 07:31 出处:网络
I have the following two classes. class Settings { function __CONSTRUCT() { echo \"Settings Construct\"; } }

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 c开发者_运维百科onstructor. Is there some way I can call the parent's constructor as well?


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消