pandaJuan
pandaJuan

Reputation: 91

Creating a new instance of an inherited class through the inherited static methods

I've got a method in my class to create a new 'self' on execution.

class foo {
    private $id;

    public function __construct( $id ) {
        $this->id = $id;
    }

    public static function byId( $id ) {
        return new self( $id );
    }  

}

And now i want to use the byId method from foo and use it in bar, by doing as such

class bar extends foo {
    public function test() {
        echo "test";
    }
}  

now I should be able to do bar::byId( id ), however this will always return the parent object and not the bar object.

How can i make sure that byId will return the object of the inherited class if it's called through it?

Upvotes: 0

Views: 61

Answers (1)

Philipp Maurer
Philipp Maurer

Reputation: 2505

Use return new static($id); instead of return new self($id);

Upvotes: 1

Related Questions