P粉5886603992023-08-30 10:02:10
In PHP, you just add an extra $
in front of a variable to make it dynamic:
$$variableName = $value;
While I don't recommend this, you can even chain this behavior:
$$$$$$$$DoNotTryThisAtHomeKids = $value;
You may, but are not required to, place $variableName
between {}
:
${$variableName} = $value;
The use of {}
is only enforced when the variable name itself is a combination of multiple values, as shown below:
${$variableNamePart1 . $variableNamePart2} = $value;
However, it is recommended to always use {}
as it is more readable.
Another reason to always use {}
is that PHP5 and PHP7 handle dynamic variables slightly differently, which can lead to different results in some cases.
In PHP7, dynamic variables, properties and methods will now be evaluated strictly from left to right, rather than the mixed special cases in PHP5. The following example shows how the order of evaluation changes.
$$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']()
P粉0432953372023-08-30 09:41:31
Wrap them in {}
:
${"file" . $i} = file($filelist[$i]);
Using ${}
is a way to create dynamic variables, a simple example:
${'a' . 'b'} = 'hello there'; echo $ab; // hello there