Assuming I have the following classes in different files:
In my case, I needed to create a method in parent class, that can call a static method with call_user_func()
in some subclass. If you know the full class name, you can call_user_func()
no problemo. The trick was to call a static method in the subclass' namespace.
So we have i.e.
\MyTools\AbstractParent
\Something\Else\Foo extends \MyTools\AbstractParent
\Something\Else\Bar extends \MyTools\AbstractParent
We now need a method in AbstractParent
. This method called from subclass Foo
will be able to call Bar::doMe()
by prepending its own namespace.
Here is how you do it with dynamic call:
namespace MyTools;
abstract class AbstractParent {
public static method doMe(){}
public function callSomethingStaticInClass($class){
// current namespace IS NOT MyTools
// so you cannot use __NAMESPACE__
$currentClass = get_class($this);
$refl = new ReflectionClass($currentClass);
$namespace = $refl->getNamespaceName();
// now we know what the subclass namespace is...
// so we prefix the short class name
$class = $namespace . '\\' . $class;
$method = 'doMe';
return call_user_func(array( $class, $method ));
}
};
namespace Something\Else;
class Foo extends AbstractParent { }
class Bar extends AbstractParent { }
$foo = new Foo();
$foo->callSomethingStaticInClass('Bar');
To make it work with a static call replace get_class($this)
with get_called_class()