简体   繁体   中英

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:

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

But for some reason when I use the $this variable, I get a parsing error. 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.

For a work around, use the KISS principle.

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. The PHP devs have been improving this recently but there is still work to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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