CodeIgniter:如何从视图的根中获取 $this?

CodeIgniter: How is $this available from the root of a view?

我了解到 $this 指的是当前对象。

但是,通常情况下,在文件的根目录中(而不是在对象中)引用 $this 会导致错误:

PHP Fatal error:  Using $this when not in object context in - on line 2

..但在视图中,我有这段代码:

<?php
$this->load->view('templates/header');
$this->load->view($view);
$this->load->view('templates/footer');

PHP 如何从 $this 引用中找到全局/单例 CI 实例?

当在控制器中调用 $this->load->view() 时,使用 PHP 的 include 命令将视图文件带入控制器 class。因此视图的代码成为控制器 class 的一部分 - 成为 $this 范围的一部分。

您视图中的代码已加载到对 eval 的调用中,或通过 Loader class 的 _ci_load 方法中的 include 加载。该方法还获取 CI 实例。

./system/core/Loader.php

在第 920 行获取实例

$_ci_CI =& get_instance();

正在将视图加载到 eval 或通过 include 在第 969 行

// If the PHP installation does not support short tags we'll
// do a little string replacement, changing the short tags
// to standard PHP echo statements.
if ( ! is_php('5.4') && ! ini_get('short_open_tag') && config_item('rewrite_short_tags') === TRUE)
{
    echo eval('?>'.preg_replace('/;*\s*\?>/', '; ?>', str_replace('<?=', '<?php echo ', file_get_contents($_ci_path))));
}
else
{
    include($_ci_path); // include() vs include_once() allows for multiple views with the same name
}