Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if an overridden parent method exists before calling it

Tags:

How would I go about ensuring that the overridden parent method exists before I call it?
I've tried this:

public function func() {     if (function_exists('parent::func')) {         return parent::func();     } } 

However the function_exists never evaluates to true.

like image 875
Nate Wagar Avatar asked Jun 15 '10 15:06

Nate Wagar


1 Answers

public function func()  {     if (is_callable('parent::func')) {         parent::func();     } } 

I use this for calling parent constructor if exists, works fine.

I also use the following as a generic version:

public static function callParentMethod(     $object,     $class,     $methodName,     array $args = [] ) {     $parentClass = get_parent_class($class);     while ($parentClass) {         if (method_exists($parentClass, $methodName)) {             $parentMethod = new \ReflectionMethod($parentClass, $methodName);             return $parentMethod->invokeArgs($object, $args);         }         $parentClass = get_parent_class($parentClass);     } } 

use it like this:

callParentMethod($this, __CLASS__, __FUNCTION__, func_get_args()); 
like image 92
Oliver Konig Avatar answered Oct 24 '22 04:10

Oliver Konig