Steven Musumeche
Steven Musumeche

Reputation: 2936

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?

Upvotes: 0

Views: 55

Answers (1)

raina77ow
raina77ow

Reputation: 106385

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.

Upvotes: 2

Related Questions