How to call grandparent method without getting E_STRICT error?

后端 未结 4 1153
有刺的猬
有刺的猬 2021-01-04 02:57

Sometimes I need to execute grandparent method (that is, bypass the parent method), I know this is code smell, but sometimes I can\'t change the other classes (frameworks, l

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-04 03:17

    You can use a separate internal method (e.g. _doStuff to complement doStuff) and call that directly from the grandchild, through the parent.

    // Base class that everything inherits
    class Grandpa  {
        protected function _doStuff() {
            // grandpa's logic
            echo 'grandpa ';
        }
    
        public function doStuff() {
            $this->_doStuff();
        }
    
    }
    
    class Papa extends Grandpa {
        public function doStuff() {
            parent::doStuff();
            echo 'papa ';
        }
    }
    
    class Kiddo extends Papa {
        public function doStuff() {
            // Calls _doStuff instead of doStuff
            parent::_doStuff();
            echo 'kiddo';
        }
    }
    
    $person = new Grandpa();
    $person->doStuff();
    echo "\n";
    $person = new Papa();
    $person->doStuff();
    echo "\n";
    $person = new Kiddo();
    $person->doStuff();
    

    shows

    grandpa
    grandpa papa
    grandpa kiddo
    

提交回复
热议问题