Reputation: 287
If you have
$a = 'World'
$str = 'Hello '.$a
$a = ' John Doe'
Is there a way in PHP that $str
would now receive the changed value from $a
?
What I know I get: $str = 'Hello World'
, what I would like: $str = 'Hello John Doe'
I know this could be done by replacing the old value with str_replace, but I would like to ask if there is a way that this var could be passed by reference or something.
Upvotes: 4
Views: 544
Reputation: 1
You can use reference at variable $a
$a = 'World';
$ra = &$a;
$str = 'Hello '.$ra;
$a = ' John Doe';
Upvotes: 0
Reputation: 40683
In short once you've set a string, its set. It doesn't get bound with arguments on anything like that.
People tend to use formatted strings for things like this:
$formattedString = "Hello %s".PHP_EOL;
$possibleValues = [ "World", "John Doe" ];
foreach ($possibleValues as $value) {
printf($formattedString, $value);
}
Prints:
Hello World
Hello John Doe
See it run at : http://sandbox.onlinephpfunctions.com/code/a9e8e7c71058b1e9a9212fbb398f9c40d20881b5
Upvotes: 8