为什么字符串插值会抛出未定义的属性

时间:2018-05-26 19:42:03

标签: php string-interpolation

我有这个代码,我有一个扩展Animal的对象Dog。

当我在Dog类中使用字符串插值来访问Animal类中的方法时,我遇到了问题,但是当我只是连接时,一切正常。 Why²

示例代码:

<?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();

 ?>

1 个答案:

答案 0 :(得分:2)

用括号括起函数调用:

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