【问题标题】:PHP: variable name as class instancePHP:变量名作为类实例
【发布时间】:2011-01-06 03:44:29
【问题描述】:

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

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

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

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

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

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM 

谢谢

【问题讨论】:

  • 有趣的是,您的代码在 PHP 5.3.1 中适用于我并且不会引发错误。
  • 可变静态类在 PHP 5.3+ 中可用,任何更低的都需要 @hobodave 提到的 call_user_func() / call_user_func_array()

标签: php static-methods instantiation php-5.2


【解决方案1】:
$test = call_user_func(array($className, 'getInstance'));

请参阅 call_user_funccallbacks

【讨论】:

  • 只有在 5.3 之前,即在 5.3+ 中您可以使用变量类名。
【解决方案2】:

您可以使用reflection 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-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 2016-11-17
    相关资源
    最近更新 更多