【发布时间】:2012-07-16 04:24:55
【问题描述】:
在 PHP 中,您可以像这样从对象实例(包含在数组中)调用类的静态方法:
$myArray['instanceOfMyClass']::staticMethod(); // works
但由于某种原因,当我使用 $this 变量时,我得到一个解析错误。例如:
$this->myArray['instanceOfMyClass']::staticMethod(); // PARSING ERROR
只是为了说明我的意思:
class MyClass{
public static function staticMethod(){ echo "staticMethod called\n"; }
}
$myArray = array();
$myArray['instanceOfMyClass'] = new MyClass;
$myArray['instanceOfMyClass']::staticMethod(); // works
class RunCode
{
private $myArray;
public function __construct(){
$this->myArray = array();
$this->myArray['instanceOfMyClass'] = new MyClass;
$this->myArray['instanceOfMyClass']::staticMethod(); // PARSING ERROR
}
}
new RunCode;
关于如何解决这个问题的任何想法?
【问题讨论】:
-
static = 使用 self:: not $this->
-
对不起?我不认为你明白我想要做什么。我只是想从 MyClass 的对象实例调用静态方法,这是 RunCode->myArray 中的一个条目。
-
使用
call_user_func(array($this->myArray['instanceOfMyClass'], 'staticMethod'));