2014-09-19 104 views
0

我想知道是否有可能更新另一個變量內的變量。更新另一個變量內的變量

下面是一個例子:

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

對我來說$dir輸出$t 15不如10

誰能幫助我?

+1

不,這個變量是什麼時候被連接成字符串 – Steve 2014-09-19 12:05:56

+0

不,這是不可能的。也許你想看看'sprintf'可以做什麼。 – CBroe 2014-09-19 12:05:57

回答

5

你誤解了那些代碼實際在做什麼。這條線:

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

不存儲參考$t爲今後的評估。它將$t評估爲當時有的任何值,並使用結果構建放置在$dir中的值。在引擎甚至將其分配給$dir之前,對$t的任何引用都會丟失。

您可以將一個變量傳遞給一個函數,您可以將變量狀態封裝在一個對象中,但是一個被評估的字符串不會引用一個變量。

0

這是不可能的。但是您可以使用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); 

?> 
0

永遠是$ T的值是什麼,在指定的時間$ DIR值爲15這將被存儲和分配。這對所有的語言都是一樣的。

0

或者如果你想,它很容易做到這一點與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