How can I call a static method from a class if all I have is a string of the class name?

后端 未结 6 1255
自闭症患者
自闭症患者 2020-12-09 01:05

How would I get something like this to work?

$class_name = \'ClassPeer\';
$class_name::doSomething();
6条回答
  •  感情败类
    2020-12-09 01:53

    To unleash the power of IDE autocomplete and error detection, use this:

    $class_name = 'ClassPeer';
    
    $r = new \ReflectionClass($class_name );
    
    // @param ClassPeer $instance
    
    $instance =  $r->newInstanceWithoutConstructor();
    
    //$class_name->doSomething();
    $instance->doSomething();
    

    Basically here we are calling the static method on an instance of the class.

提交回复
热议问题