That’s what we call interpolation of strings and only works in PHP if used double quotes or heredoc.
The PHP interpreter, when it finds a string double quotation marks or heredoc, will try to evaluate its content and, for that, will go through the string from left to right. Whenever you find the symbol, $
, interpreter will fetch as many characters as possible to build the name of the structure that was used.
echo "Saudações $nome, bem-vindo ao Stack Overflow em Português";
The interpreter will find the character $
and go through the string until the first character that will not be part of the structure name, in this case the comma, so it will be able to infer that the variable to be displayed is $nome
.
In the case of:
echo "Olá $pastor->getIdMembro(), tudo bem?";
The interpreter will not stop on the hyphen because he will understand that because it is ->
it must continue the analysis to build the property name accessed. Thus, the analysis of the name will stop only when it arrives in the parenthesis, because this does not belong to the name. In this way, what PHP does is display the value of the property $pastor->getIdMembro
followed by two parentheses. How getIdMembro
is not an object property (is a method), a string empty, and if your server is properly configured for the development environment, the alert will be displayed Undefined property: Pastor::$getIdMembro
.
How you want the parentheses to be interpreted together with the structure name, you need to inform this to the interpreter using the keys:
echo "Olá {$pastor->getIdMembro()}, tudo bem?";
Thus, the analysis will only stop when it finds the final key, }
, considering the call of the method as desired.
Not using the keys or using it is what differentiates whether we are doing a simple interpolation or a complex interpolation.
With the simple interpolation you can:
- Interpolation of simple variables:
"Olá $nome"
;
- Access indexes of a array:
"Olá $nomes[0]"
;
- Access properties of an object:
"Olá $pessoa->nome"
;
With the complex interpolation you can:
- Do everything that simple interpolation does;
- Interpolation of simple variables:
"Olá {$nome}"
;
- Access indexes of a array:
"Olá {$nomes[0]}"
;
- Access properties of an object:
"Olá {$pessoa->nome}"
;
- Access return of methods:
"Olá {$pessoa->getNome()}"
;
- Dynamically construct the accessed names:
"Olá {${$campo}}"
;
- Accessing chained structures:
"Olá {$pessoa->getEnderecos()[0]->getCidade()->getNome()}"
;
- Among other things;
put the $pastor->getIdMember() inside { }
– Ademilson Santana da Silva
good, it worked. But why ONLY in this return and in the whole SITE? What is happening here?
– Carlos Rocha
Related: Explanation about concatenation of variables in PHP
– Woss