调用从对象数组变量静态方法(Calling static method from object ar

2019-06-26 08:14发布

在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;

如何解决这个问题的任何想法?

Answer 1:

实际上,你可以使用“ - >”调用静态方法:

$this->myArray['instanceOfMyClass']->staticMethod();


Answer 2:

这是一个非常有趣的问题,它甚至可能是在PHP本身就是一个错误。

对于一个变通,用KISS原则。

class RunCode
{
    private $myArray;

    public function __construct(){
        $this->myArray = array();
        $this->myArray['instanceOfMyClass'] = new MyClass;

        $instance = $this->myArray['instanceOfMyClass']
        $instance::staticMethod();
    }
}

希望这可以帮助!



Answer 3:

你将不得不使用一个临时变量,打破了一个衬垫,如

$inst = $this->myArray['instanceOfMyClass'];
$inst::staticMethod()

这是很多情况下,PHP的编译器是不是足够聪明,了解嵌套表达式之一。 PHP的开发者最近已经改善这一点,但还有很多工作要做。



文章来源: Calling static method from object array variable