Why this string interpolation generates error

0

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 does it make a mistake when I do it?

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.
    
asked by anonymous 26.05.2018 / 21:48

1 answer

5

Because function does not run within the string (within quotation marks) the way you used it:

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

So it's as if string thinks the parentheses were not part of the method and thinks you're trying to get a property with the name getNome , but since there's no such property with this name, causes the error.

In short, within the quotation marks the parentheses are not recognized as part of what you tried to call, but rather as part of string only.

In the first example, it is out of string and concatenating it, ie the PHP interpreter parser recognizes it as a method:

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

However note that to use within quotation marks you can use the keys {} , which will make your code even more intuitive, see how it works:

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

Example:

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

Read more about keys in Complex ( curly) syntax

    
26.05.2018 / 21:59