Search code examples
phpvariablesreference

Can a variable embedded in a string be treated as a reference?


I have this tiny code:

$a = "apple";
$var = "I like the $a";
echo $var;
echo "<br>";
$a = "pear";
echo $var;

OUTPUT:
I like the apple
I like the apple

OUTPUT I NEED:
I like the apple
I like the pear

Anyone knows how can I update the var in the string dynamically?


Solution

  • Your $var string is parsed at the moment the interpreter reaches it, so changing your $a variable won't replace its value. There are many options to accomplish what you are trying to do alternatively.

    You can store your string format in $var and then apply sprintf:

    $var = 'I like the %s';
    echo sprintf($var, 'apple');
    echo sprintf($var, 'pear');
    

    Or you could just create a function that receives what you like as a parameter:

    function generateLikeString($what) {
        return "I like the $what";
    }
    
    echo generateLikeString('apple');
    echo generateLikeString('pear');