PHP Can you update var inside a string?

If you

$a = 'World'

$str = 'Hello '.$a

$a = ' John Doe'

Is there a way in PHP that $strwill now get the changed value from $a? I know that I get: $str = 'Hello World'what I would like:$str = 'Hello John Doe'

I know this can be done by replacing the old value with str_replace, but I would like to ask if there is a way to pass this var by reference or something like that.

+4
source share
2 answers

In short, as soon as you set the line, its set. This is not related to arguments for 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);
 }

Print

Hello world

Hi john doe

See how it works: http://sandbox.onlinephpfunctions.com/code/a9e8e7c71058b1e9a9212fbb398f9c40d20881b5

+8

$a

$a = 'World';
$ra = &$a;
$str = 'Hello '.$ra;
$a = ' John Doe';
0

Source: https://habr.com/ru/post/1686098/


All Articles