How to call grandparent method without getting E_STRICT error?

后端 未结 4 1130
有刺的猬
有刺的猬 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:04

    You may use ReflectionMethod->invoke()

    Example:

    age;
        }
    }
    
    class Pa extends Grandpa {
        protected $age = 'less old';
        public function sayMyAge() {
            return 'sayMyAge() in Pa should be less old. ' .
                      'My age is: ' . $this->age;
        }
    }
    
    class Son extends Pa {
        protected $age = 'younger';
        public function sayMyAge() {
            return 'sayMyAge() in Son should be younger. ' .
                      'My age is: ' . $this->age;
        }
    }
    
    $son = new Son();
    $reflectionMethod = new ReflectionMethod(get_parent_class(get_parent_class($son)), 
                                             'sayMyAge');
    echo $reflectionMethod->invoke($son);
    // returns:
    // sayMyAge() in Grandpa should be very old. My age is: younger
    

    Note: The invoked method must be public.

提交回复
热议问题