How to call grandparent method without getting E_STRICT error?

后端 未结 4 1144
有刺的猬
有刺的猬 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条回答
  •  Happy的楠姐
    2021-01-04 03:24

    You can call the grandparent directly by name (does not need Reflection, nor call_user_func).

    class Base {
        protected function getFoo() {
            return 'Base';
        }
    }
    
    class Child extends Base {
        protected function getFoo() {
            return parent::getFoo() . ' Child';
        }
    }
    
    class Grandchild extends Child {
        protected function getFoo() {
            return Base::getFoo() . ' Grandchild';
        }
    }
    

    The Base::getFoo call may look like a static call (due to the colon :: syntax), however it is not. Just like parent:: isn't static, either.

    Calling a method from the inheritance chain within a class will correctly bind the $this value, invoke it as a regular method, honour the visibility rules (e.g. protected), and is not a violation of any kind!

    This may look a bit strange at first, but, this is the way to do it in PHP.

提交回复
热议问题