繁体   English   中英

更新另一个变量内的变量

[英]Updating a variable inside another variable

我想知道是否有可能更新另一个变量内的变量。

这是一个例子:

$t = 15;
$dir ='foo and some more text'.$t.'and more foo';
$t = 10;
print_r($dir);

对我来说$dir输出$t为15而不是10。

谁能帮我这个?

您误解了该代码的实际作用。 这行:

$dir ='foo and some more text'.$t.'and more foo';

不存储对$t引用以供将来评估。 它将$t评估$t当时具有的任何值并使用该结果构造$dir的值。 在引擎甚至没有将其分配给$dir的步骤之前,对$t任何引用都会丢失。

您可以将变量传递给函数,可以将变量状态封装在对象中,但是求值字符串不会引用变量。

这是不可能的。 但是您可以使用preg_match和自定义打印功能进行类似的操作。

这只是一个如何完成的示例(警告: 实验性 ):

<?php

$blub = 15;
$test = 'foo and some more text %blub and more foo %%a';

function printv($text) {
    $parsedText = preg_replace_callback('~%([%A-Za-z0-9]+)~i', function($matches) {
        if ($matches[1][0] != '%') {
            return $GLOBALS[$matches[1]];
        }

        return $matches[1];
    }, $text);

    echo $parsedText;
}

$blub = 17;
printv($test);

?>

分配$ dir时,$ t的值为15。它将被存储和分配。 所有语言都一样。

或者,如果您愿意,可以使用匿名函数轻松实现。

 $dir = function ($t) {return 'foo and some more text'.$t.'and more foo';}
 echo $dir(10);
 //foo and some more text10and more foo
 echo $dir(15);
 //foo and some more text15and more foo

暂无
暂无

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

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