Why string interpolation throws Undefined property

I have this code, where I have an object Dog that extends Animal.

When I use string interpolation in Dog class to acess a method in Animal class, I have problems, but when I just concatenate, everything goes ok. Why²

A sample code :

<?php

class Animal
{
  private $name;
  public function getName():string
  {
    return $this->name;
  }
  public function setName($value)
  {
    $this->name=$value;
  }
}

class Dog extends Animal
{
  public function Walk()
  {
    echo $this->getName() ." is walking."; //This line works
    echo "$this->getName() is walking."; //This line throws the exception Notice: Undefined property: Dog::$getName in C:\xampp\htdocs\stackoverflow\question1\sample.php on line 27 () is walking.
  }
}

$dog = new Dog();
$dog->setName("Snoopy");
$dog->Walk();

 ?>

Upvotes: 0

Views: 398

Answers (1)

Ibu
Ibu

Reputation: 43840

Surround the function call with brackets:

class Dog extends Animal
{
  public function Walk()
  {
    echo $this->getName() ." is walking."; 
    echo "{$this->getName()} is walking."; 
  }
}

Upvotes: 2

Related Questions