alynurly
alynurly

Reputation: 1849

How to update variable variable?

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?

Upvotes: 0

Views: 126

Answers (5)

Marc B
Marc B

Reputation: 360702

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.

Upvotes: 1

What about:

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

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

Upvotes: -1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

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

Upvotes: -3

Piotr
Piotr

Reputation: 680

It's evaluated during assignment.

You can make function to deal with that.

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

Upvotes: 2

Quentin
Quentin

Reputation: 943585

$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.

Upvotes: 8

Related Questions