2013-02-13 50 views
0

为什么在类实例上下文中不要调用表格$this->className::staticMethod的工作,但$className::staticMethod表格的调用确实可行?如何调用存储为变量的类的静态方法?

在下面的例子callDoSomething2工程,但callDoSomething不起作用(我得到一个解析器错误)。我使用PHP 5.3.15版本。

<?php 
class A { 
    private $className; 

    public function __construct($className) { 
     $this->className = $className; 
    } 

    public function callDoSomething() { 
     $this->className::doSomething(); 
    } 

    public function callDoSomething2() { 
     $className = $this->className; 
     $className::doSomething(); 
    } 
} 

class B { 
    public static function doSomething() { 
     echo "hello\n"; 
    } 
} 

$a = new A('B'); 
$a->doSomething(); 
+0

重复的线路使用的东西:http://stackoverflow.com/questions/2108795/dynamic-static- method-call-in-php – 2013-02-13 22:51:20

+0

请参阅http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php – 2013-02-13 22:58:51

回答

1

callDoSomething2是做到这一点的一种方式,另将沿

call_user_func("{$this->className}::doSomething"); 
+0

你能否提供一个解释为什么callDoSomething不起作用? PHP解析器只是不能处理? – maxenglander 2013-02-13 22:55:46

+0

是的,这是一个解析错误 - PHP解析器无法处理。 – sgrif 2013-02-13 23:00:36

相关问题