Get child class namespace from superclass in PHP

后端 未结 6 1043
南旧
南旧 2020-12-09 02:24

Assuming I have the following classes in different files:



        
6条回答
  •  攒了一身酷
    2020-12-09 02:43

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

提交回复
热议问题