0

I have a string such as the following:

$s1 = "Apples";
$s2 = "$s1 are great";
echo $s2;

My understanding of PHP is that the double-quotes in the second line will cause $s1 to be evaluated within the string, and the output will be

Apples are great

However, what if I wanted to keep $s2 as a "template" where I change $s1's value and then re-evaluate it to get a new string? Is something like this possible? For example:

$s1 = "Apples";
$s2 = "$s1 are great";
echo $s2 . "\n";

$s1 = "Bananas";
$s3 = "$s2";
echo $s3 . "\n";

I find that the output for the following is:

Apples are great 
Apples are great

What I am hoping to get is more like:

Apples are great 
Bananas are great

Is such a thing possible with PHP where I can keep the "template" string the same, change the input variables, and then reevaluate to a new string? Or is this not possible with PHP?

steve8918
  • 1,820
  • 6
  • 27
  • 38

3 Answers3

2

Well, you could do something like this: (just a quick mashup).

$template = "{key} are great";
$s1 = "Apples";
$s2 = "Bananas";

echo str_replace('{key}',$s1,$template) . "\n";
echo str_replace('{key}',$s2,$template) . "\n";
OptimusCrime
  • 14,662
  • 13
  • 58
  • 96
1

You can try use anonymous function (closure) for similar result: (only above PHP 5.3!)

$s1 = function($a) { 
    return $a . ' are great';
};

echo $s1('Apples');
echo $s1('Bananas');
PazsitZ
  • 131
  • 2
0

You can also use reference passing (though it is much more commonly used in functions when you want the original modified):

<?php

$s4 = " are great";
$s1 = "Apples";
$s2 = &$s1;

echo $s2.$s4;

$s1 = "Bananas";
$s3 = $s2;
echo $s3.$s4;

?>

Output:

Apples are great
Bananas are great 
Fluffeh
  • 33,228
  • 16
  • 67
  • 80