Poc*_*ata 3 php variables codeigniter
我最近查看了CodeIgniter的代码,看它是如何工作的.
有一点我不明白为什么CodeIgniter将视图生成的所有输出存储在一个变量中并在脚本末尾输出?
这是来自./system/core/Loader.php的一段代码,位于第870行
CI源代码@ GitHub
/*
* Flush the buffer... or buff the flusher?
*
* In order to permit views to be nested within
* other views, we need to flush the content back out whenever
* we are beyond the first level of output buffering so that
* it can be seen and included properly by the first included
* template and any subsequent ones. Oy!
*/
if (ob_get_level() > $this->_ci_ob_level + 1)
{
ob_end_flush();
}
else
{
$_ci_CI->output->append_output(ob_get_contents());
@ob_end_clean();
}
Run Code Online (Sandbox Code Playgroud)
函数append_output将给定的字符串附加到CI_Output类中的变量.
是否有特殊原因这样做而不使用echo语句或仅仅是个人偏好?
有几个原因.原因是您可以加载视图并返回而不是直接输出:
// Don't print the output, store it in $content
$content = $this->load->view('email-message', array('name' => 'Pockata'), TRUE);
// Email the $content, parse it again, whatever
Run Code Online (Sandbox Code Playgroud)
第三个参数TRUE缓冲输出,因此结果不会打印到屏幕.不过你必须自己缓冲它:
ob_start();
$this->load->view('email-message', array('name' => 'Pockata'));
$content = ob_get_clean();
Run Code Online (Sandbox Code Playgroud)
另一个原因是您在发送输出后无法设置标题,因此例如您可以使用$this->output->set_content($content),然后在某些时候设置标题(设置内容类型标题,启动会话,重定向页面,等等)然后实际显示(或不显示内容.
一般来说,我发现使用任何类或函数echo或者print(在Wordpress中常见的一个例子)是非常糟糕的形式.echo $class->method();出于与上述相同的原因,我几乎总是使用它而不是让它回显我 - 就像能够将内容分配给变量而不直接溢出到输出中或创建我自己的输出缓冲区.