Idan Ptichi
Idan Ptichi

Reputation: 316

return the extending class instance from an abstract method in PHP

I have a class that extends an abstract class. does PHP allows access to the instance of the extending class from within the abstract methods?

something like:

abstract class Foo{
    protected function bar(){
        return $this;
    }
}

class Bar extends Foo{
    public function foo(){
        // this should hold Bar instance and not Foo's
        $barClassInstance = $this->bar();
    }
}

where $barClassInstance will hold the Bar class instance, instead of the abstract Foo instance?

Upvotes: 1

Views: 1037

Answers (1)

Josh J
Josh J

Reputation: 6893

Trying it out is worth a thousand stackoverflow questions

<?php

abstract class Foo{
    protected function bar(){
        echo 'Foo', PHP_EOL;
        var_dump($this);
        return $this;
    }
}

class Bar extends Foo{
    public function foo(){
        echo 'Bar', PHP_EOL;
        var_dump($this);
        // this should hold Bar instance and not Foo's
        $barClassInstance = $this->bar();
        var_dump($barClassInstance);
    }
}

$bar = new Bar();
$bar->foo();

output https://3v4l.org/b73bt

Bar
object(Bar)#1 (0) {
}
Foo
object(Bar)#1 (0) {
}
object(Bar)#1 (0) {
}

$this is a reference to the instance regardless of which subclass it is actually an instance of. There is no Foo instance because Foo cannot be instantiated, it is abstract. Even if Foo were a concrete class, you wouldn't have a Foo $this and a Bar $this in the same object. You would only have $this pointing to the specific subclass that was created.

Upvotes: 3

Related Questions