This is the code:
x = 8;
$y = "Value is $x <br>";
echo $y;
$x = $x + 2;
echo $y;
end the result is:
Value is 8
Value is 8
but I was expecting:
Value is 8
Value is 10
How to make $y behave in expected way?
It behaves in the expected way. Your expectations are wrong.
$y = "Value is $x <br>";
This is an assignment statement. It assigns a string value. That string value is the result of a string expression. The expression gets evaluated, and then the strings is baked. It won't change afterwards.
There is no standard way in PHP to have variable string values. One could create an object with __toString
and %s
placeholders for external variables. But that's kind of a big workaround.
Once you've set Y it ceases to follow x. You can never get this behavior if $y is a string, but if $y was also an int you can set it to be an alias:
$y= &$x;
In this scenario the value of $y will change as the value of $x changes.
Ben
"; } z(); $x += 2; z(); – cikatomo Dec 14 '11 at 20:37