3

在类中调用静态函数时,我在使用变量作为类名时遇到问题。我的代码如下:

class test {
     static function getInstance() {
         return new test();
     }
}

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

我必须将类名定义为变量,因为类名来自数据库,所以我永远不知道要创建哪个类的实例。

注意:目前我收到以下错误:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM 

谢谢

4

2 回答 2

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

请参阅call_user_func回调

于 2010-01-17T20:49:02.530 回答
0

您可以使用反射 API,它可以让您执行以下操作:

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

甚至:

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

两者对我来说似乎都比直接将字符串的值解释为类名或使用call_user_func和朋友要干净得多。

于 2012-05-03T08:26:43.550 回答