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

前端 未结 15 1447
滥情空心
滥情空心 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

    You can call Grandpa::__construct from where you want and the $this keyword will refer to your current class instance. But be carefull with this method you cannot access to protected properties and methods of current instance from this other context, only to public elements. => All work and officialy supported.

    Example

    // main class that everything inherits
    class Grandpa 
    {
        public function __construct()
        {
            echo $this->one; // will print 1
            echo $this->two; // error cannot access protected property
        }
    
    }
    
    class Papa extends Grandpa
    {
        public function __construct()
        {
            // call Grandpa's constructor
            parent::__construct();
        }
    }
    
    class Kiddo extends Papa
    {
        public $one = 1;
        protected $two = 2;
        public function __construct()
        {
            Grandpa::__construct();
        }
    }
    
    new Kiddo();
    

提交回复
热议问题