简体   繁体   中英

Call abstract class method from class name

I have a string containing the name of a class. This class is abstract, but has a public static method returning an instance of a child class.

abstract class MyClass {

   public static function instance() {
      return self::$inst;
   }

}

Now I need to call this method somehow and all I am given is the name of the class as a string. I can't say $class = new $className() because MyClass is abstract. Any ideas?

If you have the classname in a string and want to call an abstract method of that class, you could do the following:

$className = 'MyClass';
$instance = $className::instance();

I finally found a solution for this - Reflection.

$refClass  = new ReflectionClass('MyClass');
if ($refClass->hasMethod('instance') {
   $refMethod = new ReflectionMethod('MyClass', 'instance');
   $refMethod->invoke(null);
}

I know I am late, but if somebody is still looking, do the following:

$method = "myFunction";
$class =  "myClass";
$result = $class::$method();

So in the mentioned case use

$method = "instance";
$class = "myClass"
$instance = $class::$method();

But in your case the problem seems to be in your instance function. I guess you try to return an instance of your abstract class, which is not possible !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM