I know PHP $this
keyword refer to the current object, but I want to understand it when we use it in inheritance. For example, when I run below piece of code, it runs for infinte recursion.
<?php
class Fruit {
public function intro() {
echo "In Fruit-intro";
$this->display();
}
public function display() {
echo "Fruit-display";
}
}
class Strawberry extends Fruit {
public function display() {
parent::intro();
}
}
$strawberry = new Strawberry();
$strawberry->display();
?>
So here I was expecting $this->display
in the Fruit's intro()
method (line number:5 ) to call Fruit's display()
method but instead it is calling Strawberry's display()
method (ie calling to itself). I confirmed it when I put var_dump($this)
in Fruit's class it shows:-
object(Strawberry)#1 (0) { }
Here $this
refers to the calling object(Strawberry
) not the current object(Fruits
).
Can somebody please help me to understand this? It might be very trivial question to be asked but I want to clear my concepts. Thanks!