我想知道是否有可能更新另一個變量內的變量。更新另一個變量內的變量
下面是一個例子:
$t = 15;
$dir ='foo and some more text'.$t.'and more foo';
$t = 10;
print_r($dir);
對我來說$dir
輸出$t
15不如10
誰能幫助我?
我想知道是否有可能更新另一個變量內的變量。更新另一個變量內的變量
下面是一個例子:
$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
評估爲當時有的任何值,並使用結果構建放置在$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);
?>
永遠是$ T的值是什麼,在指定的時間$ DIR值爲15這將被存儲和分配。這對所有的語言都是一樣的。
或者如果你想,它很容易做到這一點與anonymous function。
$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
不,這個變量是什麼時候被連接成字符串 – Steve 2014-09-19 12:05:56
不,這是不可能的。也許你想看看'sprintf'可以做什麼。 – CBroe 2014-09-19 12:05:57