简体   繁体   English

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

[英]Is it possible to reference a variable before defining it?

A very simplified version of what I am trying to do: 我想要做的非常简化的版本:

$quote = "Currently showing number $i";

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

Where the $i from $quote is constantly updated with the new value. 来自$quote$i不断更新新值。

Again this is a simplified example. 这又是一个简化的例子。 I realize it could be reordered to accomplish the same thing or a str_replace() used, but for the real code it could not be accomplished. 我意识到它可以重新排序以完成相同的事情或使用的str_replace() ,但对于真正的代码,它无法完成。

You could use sprintf() / printf() which would have a placeholder that you can dynamically assign the value of $i to: 你可以使用sprintf() / printf() ,它有一个占位符,你可以动态地将$i的值赋值给:

$quote = "Currently showing number %u";

for($i=0;$i<100;$i++){
    printf($quote, $i);
}

Demo 演示

I would just do something like: 我会做的事情如下:

$quote = "Currently showing number ";

for($i=0;$i<100;$i++){
echo $quote.$i;
}

Here is your answer 这是你的答案

<?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++) {
    foreach ($matches[1] as $index => $valName) {
        if (isset(${$valName})) {
            $result = str_replace($matches[0][$index], ${$valName}, $quote);
        }
    }
    echo $result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM