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

前端 未结 15 1258
滥情空心
滥情空心 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:05
    // main class that everything inherits
    class Grandpa 
    {
        public function __construct()
        {
            $this->___construct();
        }
    
        protected function ___construct()
        {
            // grandpa's logic
        }
    
    }
    
    class Papa extends Grandpa
    {
        public function __construct()
        {
            // call Grandpa's constructor
            parent::__construct();
        }
    }
    
    class Kiddo extends Papa
    {
        public function __construct()
        {
            parent::___construct();
        }
    }
    

    note that "___construct" is not some magic name, you can call it "doGrandpaStuff".

    0 讨论(0)
  • 2020-11-28 22:06
    class Grandpa 
    {
        public function __construct()
        {}
    }
    
    class Papa extends Grandpa
    {
        public function __construct()
        {
            //call Grandpa's constructor
            parent::__construct();
        }
    }
    
    class Kiddo extends Papa
    {
        public function __construct()
        {
            //this is not a bug, it works that way in php
            Grandpa::__construct();
        }
    }
    
    0 讨论(0)
  • 2020-11-28 22:11

    Ok, Yet another ugly solution:

    Create a function in Papa like:

    protected function call2Granpa() {
         return parent::__construct();
    }
    

    Then in Kiddo you use:

    parent::call2Granpa(); //instead of calling constructor in Papa.

    I think it could work... I haven't test it, so I'm not sure if the objects are created correctly.

    I used this approach but with non-constructor functions.

    0 讨论(0)
提交回复
热议问题