PHP中的輸出緩衝很有趣。它簡化了很多事情。我使用腳本頂部的ob_start()和底部的ob_get_clean()(或任何其他函數)。輸出緩衝,分層?
在這兩個調用之間可以再次調用這些函數,而不會干擾父調用。
這種類型的代碼是否有效? (它工作正常,但...)這是一個好習慣嗎?
<?php
ob_start(); //NOTICE !!!
echo '<p>echos of the top of the script</p>';
echo GetSomeOtherData(true);
echo '<p>echos after GetSomeOtherData()</p>';
$data = ob_get_clean(); //NOTICE !!!
echo $data;
//just a function to return something, with the help of output buffering
function GetSomeOtherData($toReturn)
{
ob_start(); //NOTICE !!!
echo '<p>This has been rendered inside a function</p>';
$function_data = ob_get_clean(); //NOTICE !!!
if($toReturn===true)
{
return $function_data;
}
else
{
//may be an error | return something else
return '<p>An Error</p>';
}
}
?>