Yii 2.0架構源碼中,/yiisoft/yii2/base/View.php,看到一個函數,引入php檔案,為什麼要用ob_start,ob_get_clean?和直接引入檔案有什麼區別?
/** * Renders a view file as a PHP script. * * This method treats the view file as a PHP script and includes the file. * It extracts the given parameters and makes them available in the view file. * The method captures the output of the included view file and returns it as a string. * * This method should mainly be called by view renderer or [[renderFile()]]. * * @param string $_file_ the view file. * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file. * @return string the rendering result */public function renderPhpFile($_file_, $_params_ = []){ ob_start(); ob_implicit_flush(false); extract($_params_, EXTR_OVERWRITE); require($_file_); return ob_get_clean();}
直接這樣寫不也可以
function xx(){ return require($file);}
回複內容:
Yii 2.0架構源碼中,/yiisoft/yii2/base/View.php,看到一個函數,引入php檔案,為什麼要用ob_start,ob_get_clean?和直接引入檔案有什麼區別?
/** * Renders a view file as a PHP script. * * This method treats the view file as a PHP script and includes the file. * It extracts the given parameters and makes them available in the view file. * The method captures the output of the included view file and returns it as a string. * * This method should mainly be called by view renderer or [[renderFile()]]. * * @param string $_file_ the view file. * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file. * @return string the rendering result */public function renderPhpFile($_file_, $_params_ = []){ ob_start(); ob_implicit_flush(false); extract($_params_, EXTR_OVERWRITE); require($_file_); return ob_get_clean();}
直接這樣寫不也可以
function xx(){ return require($file);}
這段話希望可以幫到你
“Without output buffering, PHP sends data to your web server as soon as it is ready - this might be line by line or code block by code block. Not only is this slow because of the need to send lots of little bits of data, but it also means you are restricted in the order you can send data. Output buffering cures these ills by enabling you to store up your output and send to send it when you are ready to - or to not send it at all, if you so decide.”
ob_get_clean 的意思是先得到 ob_get_contents 的內容,然後再刪除緩衝區的內容 (ob_end_clean)。
也就是說:
return ob_get_clean();
等同於:
$content = ob_get_ob_get_contents();ob_end_clean();return $content;
因為直接require會輸出檔案內容,而這個函數是想返回內容,可以做進一步處理
可能是保證有輸出吧,如果使用require,而調用方法之前又有ob_start,那require是沒有輸出的.