Using braces with dynamic variable names in PHP
P粉717595985
P粉717595985 2023-08-29 12:05:01
0
2
505
<p>I'm trying to use dynamic variable names (I'm not sure what they are actually called), but something like this: </p> <pre class="brush:php;toolbar:false;">for($i=0; $i<=2; $i ) { $("file" . $i) = file($filelist[$i]); } var_dump($file0);</pre> <p>returns <code>null</code>, which tells me it doesn't work. I don't know what syntax or technology I'm looking for, which makes research difficult. <code>$filelist</code> was defined before. </p>
P粉717595985
P粉717595985

reply all(2)
P粉588660399

Overview

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.

Differences between PHP5 and PHP7

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.

Case 1: $$foo['bar']['baz']

  • PHP5 explanation: ${$foo['bar']['baz']}
  • PHP7 explanation: ${$foo}['bar']['baz']

Case 2: $foo->$bar['baz']

  • PHP5 explanation: $foo->{$bar['baz']}
  • PHP7 explanation: $foo->{$bar}['baz']

Case 3: $foo->$bar['baz']()

  • PHP5 explanation: $foo->{$bar['baz']}()
  • PHP7 explanation: $foo->{$bar}['baz']()

Case 4: Foo::$bar['baz']()

  • PHP5 explanation: Foo::{$bar['baz']}()
  • PHP7 explanation: Foo::{$bar}['baz']()
P粉043295337

Wrap them in {}:

${"file" . $i} = file($filelist[$i]);

Working example


Using ${} is a way to create dynamic variables, a simple example:

${'a' . 'b'} = 'hello there';
echo $ab; // hello there
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template