0

is it possible to update variable variable ?

$a = "Mr.John";
$b = "Dear $a, how are you doing?"; // $b = "Dear Mr.John, how are you doing?"

but if I update $a to something else $b won't change.

$a = "Mr.Gates"; //$b = "Dear Mr.John how are you doing?";

How can i update $b?

2
  • Have you tried anything? Commented Jul 21, 2014 at 14:48
  • It will automatically change. What have you tried ? Commented Jul 21, 2014 at 14:49

5 Answers 5

8

$b is not a variable variable. It is a string that was created by interpolating a variable in string literal; there is no way to update it dynamically based on another variable changing.

You should look at making $b a function (which returns a string) instead of a plain string, and then calling it when you need to use the string.

Sign up to request clarification or add additional context in comments.

Comments

2

It's evaluated during assignment.

You can make function to deal with that.

function getMeString($a) {
   return "Dear $a, how are you doing?";
}

Comments

1

PHP is not capable of time travel. Once you "embed" a variable inside a double-quoted string, that $whatever variable is GONE and only its value remains. PHP does not keep track of what it did to build the string, so if you change your "source" variable later on, your strings will not magically update themselves.

Comments

-1

What about:

$b = "Dear ".$a.", how are you doing?";

That is $b is created by concatenating "Some Text" + $b + "Some other text"

Comments

-3

UPD Sorry, in the first redaction of this comment I mixed the things up.

$a = "Mr.John";
function b() { return "Dear ".$a.", how are you doing?"; }

The variable variable is the different thing:

$a = 'john';
$$a = 'silver';  // var var

echo $john;      // silver

1 Comment

Your first code will result in same problem as OP wanted to solve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.