2012-12-13 165 views
0

我想改變原有的代碼,我有:PHP的回聲

echo "<p><strong>" . __('Area:', 'honegumi') . "</strong> " . number_format($productarea) . " m² ("; 
echo metersToFeetInches($productarea) . " ft²)" . "</p>"; 

成一個單一的回聲線所示的是:

echo "<p><strong>" . __('Area:', 'honegumi') . "</strong> " . number_format($productarea) . " m² (" . metersToFeetInches($productarea) . " ft²)" . "</p>"; 

但我發現了一些奇怪的換行符在這第二種情況下爲metersToFeetInches($ productarea)

生成的HTML:

24,757 
<p> 
<strong>Area:</strong> 
2,300 m² (ft²) 
</p> 

輸出:

 24,757 
    

Area: 2,300 m² (ft²)

我該如何解決呢?我可以閱讀的任何文件,以瞭解如何在未來自己做到這一點?

謝謝!

+2

發佈生成的HTML。 – Blender

+1

@WesleyMurch:這可能是一個本地化功能。 IIRC,Wordpress使用一個具有相似名稱的文件。 – Blender

+0

_()是gettext函數的別名@WesleyMurch –

回答

2

我很確定我知道這裏發生了什麼,你的功能metersToFeetInchesecho是一個值而不是return它。

function metersToFeetInches() { 
    echo 'OUTPUT'; 
} 

echo 'FIRST '.metersToFeetInches().' LAST'; 
// Outputs: OUTPUTFIRST LAST 

echo metersToFeetInches()實際上是多餘的。

這是因爲該函數在您構建的字符串實際輸出之前運行。請注意,您發佈的兩個示例都會遇到此問題。改爲將您的功能改爲return。然後,你使用它,像這樣的任何地方:

echo 'Something'; 
metersToFeetInches(); 
echo 'Something Else'; 

你將不得不使用echo

echo 'Something'; 
echo metersToFeetInches(); 
echo 'Something Else'; 

函數應該幾乎總是return的值。也許學到了教訓?


如果你真的處於困境而無法改變的功能,你將不得不求助於output buffering

ob_start(); 
metersToFeetInches($productarea); 
$metersToFeetInches = ob_get_clean(); 

echo "<p><strong>" . __('Area:', 'honegumi') . "</strong> " . number_format($productarea) . " m² (" . $metersToFeetInches . " ft²)" . "</p>"; 

...這是相當愚蠢不得不這樣做。

+0

謝謝韋斯利! 問題是,正如你所說,函數是回顯而不是返回。 現在工作就像一個魅力! – aurrutia