Mar*_*ark 15 php arrays static object
在PHP中,您可以从对象实例(包含在数组中)中调用类的静态方法,如下所示:
$myArray['instanceOfMyClass']::staticMethod(); // works
Run Code Online (Sandbox Code Playgroud)
但由于某种原因,当我使用$this变量时,我得到一个解析错误.例如:
$this->myArray['instanceOfMyClass']::staticMethod(); // PARSING ERROR
Run Code Online (Sandbox Code Playgroud)
只是为了说明我的意思:
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;
Run Code Online (Sandbox Code Playgroud)
关于如何解决这个问题的任何想法?
Eug*_*ene 15
你实际上可以使用" - >"来调用静态方法:
$this->myArray['instanceOfMyClass']->staticMethod();
Run Code Online (Sandbox Code Playgroud)
这是一个非常有趣的问题,它甚至可能是PHP本身的一个错误.
对于解决方法,请使用KISS原则.
class RunCode
{
private $myArray;
public function __construct(){
$this->myArray = array();
$this->myArray['instanceOfMyClass'] = new MyClass;
$instance = $this->myArray['instanceOfMyClass']
$instance::staticMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
您将不得不使用临时变量分解一个班轮,例如
$inst = $this->myArray['instanceOfMyClass'];
$inst::staticMethod()
Run Code Online (Sandbox Code Playgroud)
这是PHP的编译器不够聪明,无法理解嵌套表达式的许多情况之一.PHP开发人员最近一直在改进,但仍有工作要做.
| 归档时间: |
|
| 查看次数: |
5578 次 |
| 最近记录: |