简体   繁体   English

从对象数组变量调用静态方法

[英]Calling static method from object array variable

In PHP you can call a class's static method from an object instance (which is contained in an array) like this: 在PHP中,您可以从对象实例(包含在数组中)中调用类的静态方法,如下所示:

$myArray['instanceOfMyClass']::staticMethod(); // works

But for some reason when I use the $this variable, I get a parsing error. 但由于某种原因,当我使用$this变量时,我得到一个解析错误。 Eg: 例如:

$this->myArray['instanceOfMyClass']::staticMethod(); // PARSING ERROR

Just to illustrate what I mean: 只是为了说明我的意思:

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;

Any ideas on how to get around this? 关于如何解决这个问题的任何想法?

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

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

This is a really interesting problem, it may even be a bug in PHP itself. 这是一个非常有趣的问题,它甚至可能是PHP本身的一个错误。

For a work around, use the KISS principle. 对于解决方法,请使用KISS原则。

class RunCode
{
    private $myArray;

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

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

Hope this helps! 希望这可以帮助!

You will have to break up the one liner using a temporary variable, eg 您将不得不使用临时变量分解一个班轮,例如

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

This is one of many cases where PHP's compiler is not clever enough to understand nested expressions. 这是PHP的编译器不够聪明,无法理解嵌套表达式的许多情况之一。 The PHP devs have been improving this recently but there is still work to do. PHP开发人员最近一直在改进,但仍有工作要做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM