【问题标题】:__destruct called twice in CodeIgniter__destruct 在 CodeIgniter 中调用了两次
【发布时间】:2015-03-12 07:31:35
【问题描述】:

首先:我已经查看了所有我能找到的关于 __destruct() 和 CodeIgniter 的问题,但似乎没有一个能够解决我所看到的相同问题。

没错。那一边。我将首先显示代码,因为阅读后问题会更有意义。 (注意:一些代码被编辑了,但对这个问题并不重要。然而,Billing::index 函数在生产中和这里只包含一个空格字符


application/core/MY_Controller.php

class MY_Controller extends CI_Controller{
    public $view = '';
    public $data = array();
    public $template = '';

    function __destruct(){
        if(!is_null($this->template) && ($this->template == '')){
            $this->template = 'public';
        }

        if($this->view == ''){
            $this->view = $this->uri->segment(1,'index').'/'.$this->uri->segment(2,'index');
        }

        if(!is_null($this->template)){
            echo $this->load->view('templates/'.$this->template.'/top',$this->data,true);
        }
        echo $this->load->view('views/'.$this->view,$this->data,true);
        if(!is_null($this->template)){
            echo $this->load->view('templates/'.$this->template.'/bottom',$this->data,true);
        }
    }
}

class MY_ProtectedController extends MY_Controller{
    function __destruct(){
        parent::__destruct();
    }
}

application/controllers/billing.php

class Billing extends MY_ProtectedController{
    public function index(){ }
}

这个,完美加载。主要的“计费”页面只是 HTML,因此析构函数会触发正确的模板和视图。

但是,我很想删除多余的 public function index(){ },因为它实际上什么都不做。

所以如果我从application/controllers/billing.php 中删除它,那么它只是

class Billing extends MY_ProtectedController{ }

并访问/billing,我得到了我想要的输出,但是,我得到了它两次

如果我做一些测试回显,MY_ProtectedController::__destruct() 会被调用一次,但MY_Controller::__destruct 会被调用两次。

我的问题是:为什么会这样,能制止吗?

我对 CI 核心不是很熟悉,而且我认为当我深入挖掘到找到控制器实例时,这里的某个人可能已经得到了答案。如果我自己的挖掘出现任何问题,当然会更新此内容。

【问题讨论】:

    标签: php codeigniter destructor


    【解决方案1】:

    解决方案最终相当简单 - 但发现这一点的功劳归功于我们的其他程序员之一。

    如果我在我的 404 路由中添加一些代码来阻止自动析构函数运行,我只会得到一组输出。

    class Index extends MY_PublicController {
        public function not_found(){
            $this->cancel_destruct = TRUE;
        }
    }
    

     

    class MY_Controller extends CI_Controller{
        $this->cancel_destruct = FALSE;
        function __destruct(){
            if(!$this->cancel_destruct){
                [...]
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-25
      • 2013-01-21
      • 2012-09-08
      • 2016-04-27
      相关资源
      最近更新 更多