0

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!

Arpit Jain
  • 1,599
  • 9
  • 23
  • How can you expect `Fruit::display` to be called when you override the method in the child class `Strawberry::display`? – Ian Brindley Feb 17 '23 at 09:40
  • 4
    `$this` refers to the *current __object__*. There's only one object here, the instance of `Strawberry`. And its `display` method is `Strawberry::display`. – deceze Feb 17 '23 at 09:41
  • Thanks @deceze, for commenting, so $this keyword not bound with the Fruit class? we can't use $this keyword to access the properties and method of the Fruit class.(Yes all those properties, methods will be available in the child class). But if we use the `final` keyword to prevent any overridden of the function, then how can i use $this keyword in the parent class to refer that function? – Arpit Jain Feb 17 '23 at 09:54
  • 1
    No, it's not bound to any *class*. `$strawberry->display()` and `$this->display()` do exactly the same thing. – deceze Feb 17 '23 at 10:03

0 Answers0