Why does this string interpolation generate error

Asked

Viewed 246 times

2

I have the following PHP code :

<?php

class Animal
{
  private $nome;
  public function getNome():string
  {
    return $this->nome;
  }
  public function setNome($value)
  {
    $this->nome=$value;
  }
}

class Cachorro extends Animal
{
  public function Andar()
  {
    echo $this->getNome() ." está andando."; //Essa linha funciona
    echo "$this->getNome() está andando."; //Essa linha gera o erro: Notice: Undefined property: Dog::$getName in C:\xampp\htdocs\stackoverflow\question1\sample.php on line 27 () is walking.
  }
}

$cao = new Cachorro();
$cao->setNome("Snoopy");
$cao->Andar();

 ?>

Why is it wrong when I do?

echo $this->getNome() ." está andando."; //Essa linha funciona
echo "$this->getNome() está andando."; //Essa linha gera o erro: Notice: Undefined property: Dog::$getName in C:\xampp\htdocs\stackoverflow\question1\sample.php on line 27 () is walking.

1 answer

5


Because function does not run inside string (inside the quotes) the way you used:

echo "$this->getNome() está andando.";

So it’s like the string thought parentheses were not part of the method and think you are trying to get a property with the name getNome, but since there is no such property with this name but a method then causes the error.

In short, inside the quotes the parentheses are not recognized as part of what you tried to call, but as part of the string only.

Already in the first example this outside the string and concatenating with it, ie the parser of the PHP interpreter recognizes as a method:

echo $this->getNome() ." está andando.";

However note that to use inside quotes you can use the keys {}, what will make even more intuitive your code, see that this way works:

echo "{$this->getNome()} está andando.";

Example:

class Cachorro extends Animal
{
    public function Andar()
    {
        echo "{$this->getNome()} está andando.";
    }
}

Read more about the keys on Complex (Curly) syntax

Browser other questions tagged

You are not signed in. Login or sign up in order to post.