Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these PHP string interpolation syntaxes

What is the difference between "${varname}" and "{$varname}" in PHP's string interpolation? (notice the position of the $)

The php docs say that you can use either, but doesn't clearly explain what the difference between these two methods is. Is there actually a difference?

like image 936
nevada_scout Avatar asked Sep 16 '16 13:09

nevada_scout


People also ask

What is string interpolation PHP?

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

What is Heredoc and Nowdoc in PHP?

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping.

What is PHP string function?

According to string functions in php, in programming languages, string functions are used to modify a string or query knowledge about a string (some do both).... The length (string) function is the most basic example of a string function. The length of a string literal is returned by this function.

Which strings do not interpolate variables?

Interpolation: The variable parsing is allowed when the string literal is enclosed with double quotes or with heredocs. Single quoted string or nowdocs, does not supports variable interpolation.


1 Answers

The first one is interpolation plus variable variable (dynamic variable), meaning you can use expressions here to define the name of the variable you want to interpolate "${func()}" While the second one syntax is used to distinct variable from the text "some{$variable}text". You can actually combine them:

function func(){
    return 'foo';
}
$foo = 'bar';
echo "some{${func()}}text";

Outputs: somebartext

like image 99
Alexey Chuhrov Avatar answered Sep 20 '22 13:09

Alexey Chuhrov