简体   繁体   中英

Accessing static method of class object

I'm having a very strange syntax error inside of a class when trying to access a static method of a class variable.

class VendorImport {
    //$factory is an instance of another class with a static method get()
    protected $factory;

    public function getInstance() {
        //method 1 works
        $factory = $this->factory;
        return $factory::get();

        //method 2 throws a syntax error
        return $this->factory::get();
    }
}

What is the proper syntax for method 2?

Just use regular syntax for calling non-static methods - it's applicable for static ones too:

// instead of `return $this->factory::get();`
return $this->factory->get();

Demo . There's a drawback, though: now it's not obvious a static method gets called here. But then again, one cannot define two methods - static and non-static - under the same name in the same class.

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