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?

3

3 Answers 3

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";
Sign up to request clarification or add additional context in comments.

Comments

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');

Comments

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.