What’s the difference between using and not using keys in string interpolation in PHP?

Asked

Viewed 82 times

5

What’s the difference between?

$fruta = 'tomate';
echo "{$fruta} é fruta<br>";
echo "$fruta é fruta<br>";

Why some programmers use the keys ({}) if the result without them is the same?

  • 1

    Actually this is an interpolation and not concatenation, which is done with the . in php

1 answer

4

According to the documentation, this call feature interprets variables within strings. But it can also be called interpolation. This is not an example of concatenation. Although they are used to make things equal, they are different.

Still according to the documentation, there are two ways to interpret variables in strings, a simple syntax and the complex syntax.

In simple syntax, the interpreter will search for dollar signs ($) in the string and will replace with the value of the identifier. An example:

$a = 10;
$str = "O número é $a. \n";

echo $str;

See working on Repl.it

In the above example, keys are optional, since no complex expression is being used. Therefore, $a and {$a} produce the same result.


Complex syntax, in turn, should be used for more complex expressions, such as accessing values from arrays or properties of objects that require keys. For example:

class Person {
  function __construct($name) {
    $this->name = $name;
  }
}

$person = new Person('Luiz');

$array = ['foo' => 'bar'];

echo "Olá, {$person->name}! \n";
echo "Foo {$array['foo']}! \n";

See working on Repl.it

In the above example, keys are mandatory. Otherwise, you will receive an error from parse.


Note that this type of syntax does not work on strings with single quotes.

Why some programmers use the keys ({}) if the result without them is the same?

As we have seen above, keys are needed for complex expressions. For simple expressions, however, they are likely to be used to maintain a standard.

Browser other questions tagged

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