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

前端 未结 15 1410
滥情空心
滥情空心 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 21:53

    Another option that doesn't use a flag and might work in your situation:

    GrandpaSetup();
        }
    
        public function GrandpaSetup(){
            $this->prop1 = 'foo';
            $this->prop2 = 'bar';
        }
    }
    
    class Papa extends Grandpa
    {
        public function __construct()
        {
            // call Grandpa's constructor
            parent::__construct();
            $this->prop1 = 'foobar';
        }
    
    }
    class Kiddo extends Papa
    {
        public function __construct()
        {
            $this->GrandpaSetup();
        }
    }
    
    $kid = new Kiddo();
    echo "{$kid->prop1}\n{$kid->prop2}\n";
    

提交回复
热议问题