2013-07-28 17 views
0

想象一下以下內容:如何在不存在重複的情況下將回聲存儲在PHP中的變量中?

<?php 
echo 'foo'; 
echo 'bar'; 
?> 

簡單,對不對?現在,如果在這個簡單的腳本結束時,我需要做什麼都有了,我回蕩在該腳本中的變量,如:

<?php 
echo 'foo'; 
echo 'bar'; 
// $end // which contains 'foobar'; 
?> 

我嘗試這樣做:

<?php 
$end = NULL; 
echo $end .= 'foo'; // this echoes foo 
echo $end .= 'bar'; // this echoes foobar (this is bad) 
// $end // which contains 'foobar' (this is ok); 
?> 

但它不因爲它附加了數據,因此回聲附加的數據(重複)。任何方式來做到這一點?

編輯:我不能使用OB,因爲我已經以不同的方式在腳本中使用它(我在瀏覽器中模擬CLI輸出)。

+0

爲什麼不會你創建一個回波和追加輸出的功能? –

+0

輸出緩衝可以嵌套 – Scuzzy

回答

0

我真的不知道你正在試圖完成的任務,但考慮到輸出緩衝:

<?php 
ob_start(); 
echo "foo"; 
echo "bar"; 

$end = ob_get_clean(); 
echo $end; 
+0

我不能使用OB,因爲我已經以不同的方式在腳本中使用它(我在瀏覽器中模擬CLI輸出)。 –

+1

@RichardRodriguez輸出緩衝可以嵌套。 – dialer

1

顯然我是誤解:那麼我建議這樣的:

<?php 
    $somevar = ''; 
    function record_and_echo($msg,$record_var) { 
     echo($msg); 
     return ($msg); 
    } 
    $somevar .= record_and_echo('foo'); 
    //...whatever else// 
    $somevar .= record_and_echo('bar'); 
?> 

老: 除非我誤會這會做到這一點:

<?php 
    $output = '' 
    $output .= 'foo'; 
    $output .= 'bar'; 
    echo $output; 
?> 
+1

這不是他想做的事情,他想在$ end中連接'foo'和'bar',但在第二個回顯中只是'bar' –

+0

嗯,在重讀時我會明白你的意思@Amine ;看我的編輯。 –

+0

是的,這是一個更好的答案!但是...該函數需要2個參數,而第二個不使用...?! –

0

OB可以嵌套:

<?php 
ob_start(); 

echo 'some output'; 

ob_start(); 

echo 'foo'; 
echo 'bar'; 

$nestedOb = ob_get_contents(); 
ob_end_clean(); 

echo 'other output'; 

$outerOb = ob_get_contents(); 
ob_end_clean(); 

echo 'Outer output: ' . $outerOb . '' . "\n" . 'Nested output: ' . $nestedOb; 

結果:

Outer output: some outputother output; 
Nested output: foobar 
相關問題