我有一个如下字符串:
$s1 = "Apples";
$s2 = "$s1 are great";
echo $s2;
我对PHP的理解是,第二行中的双引号将导致$ s1在字符串中被计算,输出将是
Apples are great
但是,如果我想将$ s2保留为“模板”,我更改$ s1的值,然后重新评估它以获得新的字符串,该怎么办?这样的事情可能吗?例如:
$s1 = "Apples";
$s2 = "$s1 are great";
echo $s2 . "\n";
$s1 = "Bananas";
$s3 = "$s2";
echo $s3 . "\n";
我发现以下内容的输出是:
Apples are great
Apples are great
我希望得到的更像是:
Apples are great
Bananas are great
使用PHP可以保持“模板”字符串相同,更改输入变量,然后重新评估为新字符串吗?或者PHP不可能这样做?
答案 0 :(得分:2)
嗯,你可以这样做:(只是一个快速的混搭)。
$template = "{key} are great";
$s1 = "Apples";
$s2 = "Bananas";
echo str_replace('{key}',$s1,$template) . "\n";
echo str_replace('{key}',$s2,$template) . "\n";
答案 1 :(得分:1)
您可以尝试使用anonymous function (closure)获得类似结果: (仅高于PHP 5.3!)
$s1 = function($a) {
return $a . ' are great';
};
echo $s1('Apples');
echo $s1('Bananas');
答案 2 :(得分:0)
您也可以使用引用传递(尽管在您希望修改原始文件时,它更常用于函数中):
<?php
$s4 = " are great";
$s1 = "Apples";
$s2 = &$s1;
echo $s2.$s4;
$s1 = "Bananas";
$s3 = $s2;
echo $s3.$s4;
?>
输出:
Apples are great
Bananas are great