无法在php函数中运行db查询

无法在php函数中运行db查询,php,mysql,codeigniter,Php,Mysql,Codeigniter,我在我的视图中创建了一个函数,并尝试在php函数中进行查询,但我不知道我遇到了在我整个职业生涯中从未出现过的意外错误。有人能帮我摆脱这个错误吗 Severity: Error --> Using $this when not in object context /application/views/includes/create_calendar.php 51 这是我的控制器 class Booking extends CI_Controller { public functio

我在我的视图中创建了一个函数,并尝试在php函数中进行查询,但我不知道我遇到了在我整个职业生涯中从未出现过的意外错误。有人能帮我摆脱这个错误吗

Severity: Error --> Using $this when not in object context /application/views/includes/create_calendar.php 51
这是我的控制器

class Booking extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->helper(array("form", "url"));
        $this->load->library('session');
        $this->load->database();
    }

    public function get_calendar() {
        $this->load->view('includes/create_calendar');
    }
}
这是我试图在其中运行查询views/includes/create_calendar.php的文件

function getCalender($year = '',$month = '') {  
   $sql       = $this->db->get('calendar');
   if($day == $sql->row()->day_off) { $per_off = $sql->row()->per_off; }

                        echo "<p>".$day." Off</p>";
}

在CodeIgniter使用中,如果需要使用超级对象中可用的类之一,则必须首先获取超级对象的实例:

$CI =& get_instance();
$CI->db->get('calendar');
甚至可能无法加载此DB类。如果是这种情况,则在使用db之前:

$CI->load->database();
为了澄清这一点,一旦进入该函数,就从变量范围中删除了$this,如下面的简单测试:

class Test {

    public $foo = 'bar';

    public function index() {
        function baz(){
            return $this->foo;
        }
        echo baz();
    }
}

$t = new Test;
$t->index();
您可以执行以下操作,但这真的很麻烦:

class Test {

    public $foo = 'bar';

    public function index() {
        function baz($x) {
            return $x->foo;
        }
        echo baz($this);
    }
}

$t = new Test;
$t->index();

对你来说,最好的办法是找到另一种更干净的方法来做你正在做的事情。您通常不希望在视图中调用数据库和函数。这与MVC的功能背道而驰。

但是很多次我试图在视图中调用一个查询,它运行正常。为什么现在出现了这个错误?基于您的代码,我无法告诉您原因。我可以告诉你,这就是当CodeIgniter超级对象不存在时,你如何找到它的方法。这可能发生在图书馆、助手或其他任何地方。我想可变范围可能在这里发挥作用。因为你在一个函数中。我更新了我的答案。要了解其发生的原因,请参见以下内容: