是否可以在定义变量之前引用它?

我正在尝试做的一个非常简化的版本:


$quote = "Currently showing number $i";


for($i=0;$i<100;$i++){

echo $quote;

}

其中$ifrom$quote不断更新为新值。


这又是一个简化的例子。我意识到它可以重新排序以完成相同的事情或str_replace()使用过,但对于真正的代码,它无法完成。


温温酱
浏览 194回答 3
3回答

慕斯王

您可以使用sprintf()/printf()它将有一个占位符,您可以动态地将值分配$i给:$quote = "Currently showing number %u";for($i=0;$i<100;$i++){&nbsp; &nbsp; printf($quote, $i);}

斯蒂芬大帝

这是你的答案<?php$quote = 'Currently showing number $i';$pattern = '/\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/';preg_match_all($pattern, $quote, $matches);for ($i=0; $i<100; $i++) {&nbsp; &nbsp; foreach ($matches[1] as $index => $valName) {&nbsp; &nbsp; &nbsp; &nbsp; if (isset(${$valName})) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $result = str_replace($matches[0][$index], ${$valName}, $quote);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; echo $result;}
打开App,查看更多内容
随时随地看视频慕课网APP