In one of the answers to the question about the HEREDOC syntax , an interesting expression was given:

echo <<<EOT One month ago was ${!${''} = date('Ymd H:i:s', strtotime('-1 month'))}. EOT; 

What is this "black magic" (according to the author)? and how does it work?

    1 answer 1

    In PHP, there are variables that point to another variable by name. They are written as $$var . That is, we can write this:

     $a = 123; $b = 'a'; print $$b; 

    This code will output 123

    Similarly, we can write ${$b} - this will also be $a . And if we write ${'a'} - the same thing.

    Now let's look at magic. ${!${''} = 'какая-то ненулевая строка'} - means "variable value !'какая-то ненулевая строка' . Since the negation of a non-zero string - is reduced to an empty string, the variable name will be an empty string. And we in the same expression, this variable was assigned the value we need, so the record ${!${''} = (какое-то выражение)} equivalent to the variable containing the result of this expression (if its result is not reduced to false , then we get an error).

    By the way, if you want to display the value in this way, which may turn out to be empty, you can add some more magic ${!${''} = ${1} = (какое-то выражение)}

    Ps. Where does it say that a variable name cannot be a number?

    Pps. Postscript is a joke of course. I know where it is written and I know that $ 1 is an invalid variable :)

    • > Since the negation of a nonzero string is an empty string, the variable name is an empty string. And we in the same expression of this variable assigned the value we need. - Unclear. - Sergiks September
    • The variable name in PHP cannot be an empty string, and cannot begin with a digit. - Sergiks September
    • @Sergiks Facts stubborn thing ${''} = 'test'; print ${''}; ${''} = 'test'; print ${''}; - displays abc - tutankhamun
    • understood thanks! :) discussion of a similar question in English. - Sergiks September
    • one
      @Sergiks about the variable name. As I understand it, this is a limitation of the parser only, by the time the key is accessed by the variables variable, the key is apparently not checked - tutankhamun