doumo3903
2011-02-20 20:59
浏览 231
已采纳

使用变量类名访问静态方法(PHP)

I am trying to access a static method, but using a variable as the class name. Is this possible? I seem to be having issues with it. I want to be able to do something like this:

class foo {
    public static function bar() {
        echo 'test';
    }
}

$variable_class_name = 'foo';
$variable_class_name::bar();

And I want to be able to do similar using static variables as well.

图片转代码服务由CSDN问答提供 功能建议

我正在尝试访问静态方法,但使用变量作为类名。 这可能吗? 我似乎遇到了问题。 我希望能够做到这样的事情:

  class foo {
 public static function bar(){
 echo'test'; 
} 
}  
 
 $ variable_class_name ='foo'; 
 $ variable_class_name :: bar(); 
   
 
 

我希望能够使用静态变量做类似的事情 同样。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongwuwei0718 2011-02-20 21:08
    已采纳

    That syntax is only supported in PHP 5.3 and later. Previous versions don't understand that syntax, hence your parse error (T_PAAMAYIM_NEKUDOTAYIM refers to the :: operator).

    In previous versions you can try call_user_func(), passing it an array containing the class name and its method name:

    $variable_class_name = 'foo';
    call_user_func(array($variable_class_name, 'bar'));
    
    已采纳该答案
    打赏 评论
  • dongshi1188 2011-02-20 22:14

    You can use reflection for PHP 5.1 and above:

    class foo {
        public static $bar = 'foobar';
    }
    
    $class = 'foo';
    $reflector = new ReflectionClass($class);
    echo $reflector->getStaticPropertyValue('bar');
    
    > foobar
    
    打赏 评论

相关推荐 更多相似问题