Checking if an overridden parent method exists before calling it

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());

The way to do that, is:

if (method_exists(get_parent_class($this), 'func')) {
    // method exist
} else {
   // doesn't
}

http://php.net/manual/en/function.method-exists.php
http://php.net/manual/en/function.get-parent-class.php

Tags:

Php