How do I get a PHP class constructor to call its parent's parent's constructor?

前端 未结 15 1390
滥情空心
滥情空心 2020-11-28 21:38

I need to have a class constructor in PHP call its parent\'s parent\'s (grandparent?) constructor without calling the parent constructor.

//         


        
15条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 22:01

    I agree with "too much php", try this:

    class Grandpa 
    {
        public function __construct()
        {
            echo 'Grandpa
    '; } } class Papa extends Grandpa { public function __construct() { echo 'Papa
    '; parent::__construct(); } } class Kiddo extends Papa { public function __construct() { // THIS IS WHERE I NEED TO CALL GRANDPA'S // CONSTRUCTOR AND NOT PAPA'S echo 'Kiddo
    '; Grandpa::__construct(); } } $instance = new Kiddo;

    I got the result as expected:

    Kiddo

    Grandpa

    This is a feature not a bug, check this for your reference:

    https://bugs.php.net/bug.php?id=42016

    It is just the way it works. If it sees it is coming from the right context this call version does not enforce a static call.

    Instead it will simply keep $this and be happy with it.

    parent::method() works in the same way, you don't have to define the method as static but it can be called in the same context. Try this out for more interesting:

    class Grandpa 
    {
        public function __construct()
        {
            echo 'Grandpa
    '; Kiddo::hello(); } } class Papa extends Grandpa { public function __construct() { echo 'Papa
    '; parent::__construct(); } } class Kiddo extends Papa { public function __construct() { // THIS IS WHERE I NEED TO CALL GRANDPA'S // CONSTRUCTOR AND NOT PAPA'S echo 'Kiddo
    '; Grandpa::__construct(); } public function hello() { echo 'Hello
    '; } } $instance = new Kiddo;

    It also works as expected:

    Kiddo

    Grandpa

    Hello

    But if you try to initialize a new Papa, you will get an E_STRICT error:

    $papa = new Papa;
    

    Strict standards: Non-static method Kiddo::hello() should not be called statically, assuming $this from incompatible context

    You can use instanceof to determine if you can call a Children::method() in a parent method:

    if ($this instanceof Kiddo) Kiddo::hello();
    

提交回复
热议问题