【问题标题】:how do i extend a class in codeigniter?如何在 codeigniter 中扩展一个类?
【发布时间】:2014-07-05 20:01:42
【问题描述】:

这是我的控制器:普通:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Common extends CI_Controller {

    public function __construct() { 

        parent::__construct();

    }
    public function test(){
        echo 1;
    }

}

这是第二个控制器(寄存器):

class Register extends Common {

    public function __construct() { 

        parent::__construct();

    }
    public function user_registration(){
        $this->test();
    }
}

当我访问 user_registration 函数时,它显示了这个错误: 致命错误:在第 3 行的 /home/attilana/domains/attila-naghi.com/public_html/application/controllers/register.php 中找不到“Common”类

如何在类寄存器的 user_registration 函数中从类 common 访问 test() 函数?

【问题讨论】:

    标签: codeigniter class controller extends


    【解决方案1】:

    在 Codeigniter 中,即使在这样的示例中,也无法从另一个控制器调用控制器,因为它不允许请求中有多个控制器实例。由于这种情况,您实际上有三个主要选择。

    首先,您可以使用 MY_ 前缀扩展 Codeigniter 的基本控制器 CI_Controller,以便 Codeigniter 将其识别为通用基类。这里的主要思想是编写在大多数控制器中通用的方法。

    如果我们看一下您的示例并尝试按照上述方式进行调整:

    最初,您需要扩展 CI_Controller 类:

    class MY_Controller extends CI_Controller {
    
        public function __construct() { 
            parent::__construct();
        }
    
        public function test(){
            echo 1;
        }
    
    }
    

    其次,创建您的注册控制器如下:

    class Register extends MY_Controller {
    
        public function __construct() { 
            parent::__construct();
        }
    
        public function user_registration(){
            $this->test();
        }
    }
    

    另一种可能性是您可以创建一个帮助程序并全局调用该函数,或者您可以创建一个库并将其加载到您的控制器中并调用它。

    有关更多信息,您可以从此处阅读:http://ellislab.com/codeigniter/user-guide/general/core_classes.html 或从旧文档:https://github.com/EllisLab/CodeIgniter/wiki/MY-Controller

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-21
      • 2013-04-27
      • 2013-03-09
      • 2017-03-11
      • 2013-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多