PHP 动态字符串更新参考 [英] PHP dynamic string update with reference
问题描述
有没有办法做到这一点:
Is there any way to do this:
$myVar = 2;
$str = "I'm number:".$myVar;
$myVar = 3;
echo $str;
输出将是:"I'm number: 3";
我想要一个字符串,它的一部分就像一个指针,它的值将通过对引用变量的最后一次修改来设置.
I'd like to have a string where part of it would be like a pointer and its value would be set by the last modification to the referenced variable.
例如,即使我这样做:
$myStr = "hi";
$myStrReference = &$myStr;
$dynamicStr = "bye ".$myStrReference;
$myStr = "bye";
echo $dynamicStr;
这将输出bye hi
",但由于最后一次更改,我希望它是bye bye
".我认为问题在于将指针连接到字符串时,指针的值是所使用的值.因此,无法使用连接后设置的值输出字符串.
This will output "bye hi
" but I'd like it to be "bye bye
" due to the last change. I think the issue is when concatenating a pointer to a string the the pointer's value is the one used. As such, It's not possible to output the string using the value set after the concatenation.
有什么想法吗?
更新:$dynamicStr
将被附加到 $biggerString
和最后 $finalResult
($biggerString+$dynamicStr
) 将回显给用户.因此,我唯一的选择是做某种 echo eval($finalResult)
其中 $finalResult
里面会有一个 echo($dynamicStr)
和 $dynamicStr='$myStr'
(按照 Lawson 的建议),对吗?
Update: the $dynamicStr
will be appended to a $biggerString
and at the end the $finalResult
($biggerString+$dynamicStr
) will be echo to the user. Thus, my only option would be doing some kind of echo eval($finalResult)
where $finalResult
would have an echo($dynamicStr)
inside and $dynamicStr='$myStr'
(as suggested by Lawson), right?
更新:
$myVar = 2;
$str = function() use (&$myVar) {
return "I'm number $myVar";
};
$finalStr = "hi ".$str();
$myVar = 3;
echo $finalStr;
我希望它输出:我是 3 号"而不是我是 2 号"......但事实并非如此.
I'd like for this to ouput: "hi I'm number 3" instead of "hi I'm number 2"...but it doesn't.
推荐答案
这里的问题是,一旦一个变量被赋值(在你的例子中是一个字符串),它的值在再次修改之前不会改变.
The problem here is that once a variable gets assigned a value (a string in your case), its value doesn't change until it's modified again.
>
你可以使用匿名函数来完成类似的事情:
You could use an anonymous function to accomplish something similar:
$myVar = 2;
$str = function() use (&$myVar) {
return "I'm number $myVar";
};
echo $str(); // I'm number 2
$myVar = 3;
echo $str(); // I'm number 3
当函数被分配给 $str
时,它会保持变量 $myVar
从内部访问.在任何时间点调用它都会使用 $myVar
的最新值.
When the function gets assigned to $str
it keeps the variable $myVar
accessible from within. Calling it at any point in time will use the most recent value of $myVar
.
更新
关于你的最后一个问题,如果你想进一步扩展字符串,你可以创建另一个包装器:
Regarding your last question, if you want to expand the string even more, you can create yet another wrapper:
$myVar = 2;
$str = function() use (&$myVar) {
return "I'm number $myVar";
};
$finalStr = function($str) {
return "hi " . $str();
}
$myVar = 3;
echo $finalStr($str);
这篇关于PHP 动态字符串更新参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!