In PHP, you can just put an extra $
in front of a variable to make it a dynamic variable :
$$variableName = $value;
While I wouldn't recommend it, you could even chain this behavior :
$$$$$$$$DoNotTryThisAtHomeKids = $value;
You can but are not forced to put $variableName
between {}
:
${$variableName} = $value;
Using {}
is only mandatory when the name of your variable is itself a composition of multiple values, like this :
${$variableNamePart1 . $variableNamePart2} = $value;
It is nevertheless recommended to always use {}
, because it's more readable.
Another reason to always use {}
, is that PHP5 and PHP7 have a slightly different way of dealing with dynamic variables, which results in a different outcome in some cases.
In PHP7, dynamic variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the mix of special cases in PHP5. The examples below show how the order of evaluation has changed.
$$foo['bar']['baz']
${$foo['bar']['baz']}
${$foo}['bar']['baz']
$foo->$bar['baz']
$foo->{$bar['baz']}
$foo->{$bar}['baz']
$foo->$bar['baz']()
$foo->{$bar['baz']}()
$foo->{$bar}['baz']()
Foo::$bar['baz']()
Foo::{$bar['baz']}()
Foo::{$bar}['baz']()