Home  >  Q&A  >  body text

Using braces with dynamic variable names in PHP

<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粉717595985P粉717595985440 days ago464

reply all(2)I'll reply

  • P粉588660399

    P粉5886603992023-08-30 10:02:10

    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']()

    reply
    0
  • P粉043295337

    P粉0432953372023-08-30 09:41:31

    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

    reply
    0
  • Cancelreply