在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;
关于如何绕过这个问题有什么想法吗?
您实际上可以使用"->"来调用静态方法:
$this->myArray['instanceOfMyClass']->staticMethod();
这是一个非常有趣的问题,甚至可能是PHP本身的一个bug。
对于变通办法,请使用KISS原则。
class RunCode
{
private $myArray;
public function __construct(){
$this->myArray = array();
$this->myArray['instanceOfMyClass'] = new MyClass;
$instance = $this->myArray['instanceOfMyClass']
$instance::staticMethod();
}
}
希望这能有所帮助!
您将不得不使用临时变量(例如)来分解一行
$inst = $this->myArray['instanceOfMyClass'];
$inst::staticMethod()
这是PHP编译器在理解嵌套表达式方面不够聪明的许多情况之一。PHP开发人员最近一直在改进这一点,但仍有工作要做。