0

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?

cikatomo
  • 1,620
  • 2
  • 23
  • 32

2 Answers2

3

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.

mario
  • 144,265
  • 20
  • 237
  • 291
  • This is the workaround: $x = 8; function z() { global $x; echo "Value is $x
    "; } z(); $x += 2; z();
    – cikatomo Dec 14 '11 at 20:37
  • 1
    Okay, that works too. That's less of a workaround and more of an actual implementation. You could use a closure btw to the same effect: `$z = function() use (&$x) { return "Value is $x"; }; $x=22; print $z();` - Eschews singular vars in the global scope. – mario Dec 14 '11 at 20:41
0

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

Ben D
  • 14,321
  • 3
  • 45
  • 59