为什么CodeIgniter将输出存储在变量中?

时间:2012-05-22 19:04:03

标签: php codeigniter variables

我最近查看了CodeIgniter的代码,看看它是如何工作的。

我不明白的一件事是CodeIgniter将视图生成的所有输出存储在单个变量中并在脚本末尾输出?

这是来自./system/core/Loader.php 870行的一段代码。 CI Source code @ 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();
}

函数append_output将给定的字符串附加到CI_Output类中的变量 有没有特别的理由这样做而不使用echo语句,还是仅仅是个人偏好?

2 个答案:

答案 0 :(得分:6)

有几个原因。原因是您可以加载视图并将其返回而不是直接输出:

// 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

第三个参数TRUE缓冲输出,因此结果不会打印到屏幕上。但是你必须自己缓冲它:

ob_start();
$this->load->view('email-message', array('name' => 'Pockata'));
$content = ob_get_clean();

另一个原因是您在发送输出后无法设置标头,因此例如您可以使用$this->output->set_content($content),然后在某个时刻设置标头(设置内容类型标头,启动会话,重定向页面) ,无论如何)然后实际显示(或不显示)内容。

一般来说,我觉得让任何类或函数使用echoprint(在Wordpress中常见的一个例子)非常糟糕。由于上面提到的相同原因,我几乎总是使用echo $class->method();而不是让它回显我 - 就像能够将内容分配给变量而不直接溢出到输出中或创建我自己的输出缓冲区。

答案 1 :(得分:4)

答案在于您帖子中的评论。

/**
* 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!
*/

这样你就可以了:

$view = $this->load->view('myview', array('keys' => 'value'), true);
$this->load->view('myotherview', array('data' => $view));
相关问题