Why script

<?php $x="2"; $y="3"; $z="\x$x$y"; echo $z; ?> 

Print the string \x23 , not the # character? How does variable substitution in a string work in PHP ?

  • Explain why you decided that a # should be displayed? - PinkTux
  • I thought that the interpreter FIRST substituted the value of the variables $ x and $ y, and THEN starts reading the newly received string, sees \ x23 and thinks "yes this is the # symbol". and slap him there - Dimon
  • I don’t know where this information comes from, but I assure you - the interpreter is not so ... uh ... original :) And how interpolation of strings actually works (not only in PHP, but in many languages ​​in principle) can be found on corner, prototyping the search query "string interpolation." And do not invent anything, everything is clearly painted. - PinkTux
  • nothing is clearly defined. If you enter "interpolation of variables in php", it will produce dozens of REVIEW identical articles that are copied from any one source - Dimon
  • Tyk the mouse - PinkTux

1 answer 1

I thought that the interpreter FIRST substituted the value of the variables $ x and $ y, and THEN starts reading the newly received string, sees \ x23 and thinks "yes this is the # symbol". and put him there

No, interpolation is always done in a single pass. At least from the considerations of elementary logic: multi-pass interpolation can (and will) lead to unpredictable results, which are simply not foreseeable in most cases. Not to mention the fact that it will slow down the work of the interpreter, and most importantly, it is simply not necessary.

So in the simplest case, a banal string substitution is made and nothing else. Details are described in the PHP manual, section "Variable Processing" .

In more complex cases, sets of rules are used, which are described in the section “Complex (curly) syntax” there.