开发者

PHP: variable name as class instance

开发者 https://www.devze.com 2022-12-16 12:34 出处:网络
Im having a problem with using a variable as the class name when calling a static function within the class. My code is as follows:

Im having a problem with using a variable as the class name when calling a static function within the class. My code is as follows:

class test {
     static function getInstance() {
         return new test();
    开发者_如何学C }
}

$className = "test";
$test = $className::getInstance();

Ive got to define the class name to a variable as the name of the class is coming from a database so i never know what class to create an instance of.

note: currently i am getting the following error:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM 

Thanks


$test = call_user_func(array($className, 'getInstance'));

See call_user_func and callbacks.


You could use the reflection API, that would let you do something like:

$className = 'Test';
$reflector = new ReflectionClass($className);
$method = $reflector->getMethod('getInstance');
$instance = $method->invoke(null);

or even:

$className = 'Test';
$reflector = new ReflectionClass($className);
$instance = $reflector->newInstance(); 
// or $instance = $reflector->newInstanceArgs([array]);
// or $instance = $reflector->newInstanceWithoutConstructor();

Both seem a lot cleaner to me than just interpreting the value of a string directly as a class name or using call_user_func and friends.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号