CodeIgniter控制器构造函数 [英] CodeIgniter Controller Constructor

查看:92
本文介绍了CodeIgniter控制器构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Codeigniter的新手,我想知道控制器中构造函数的含义是什么.我在codeigniter教程中看到了以下代码-

I'm very new to codeigniter , I wanted to know what is the meaning of a constructor in a controller . I saw the following code in a codeigniter tutorial -

class upload extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->helper(form);
    }

    // rest of the class...

我的问题是何时调用构造函数-每次控制器处理请求时都会调用该构造函数(例如,控制器类针对收到的每个请求实例化吗?)

My question is when is the constructor invoked - is it called every time the controller serves a request (e.g the controller class is instantiated for each request it receives?)

推荐答案

嗯,这是一个更通用的PHP问题.无论如何,是的,在类的每个实例化之后,魔术方法__construct()都会被(自动)调用,如您在手册中所看到的:

Well, that's a more general PHP question. Anyway, yes, the magic method __construct() is called (automatically) upon each instantiation of the class, as you can see in the manual: http://www.php.net/manual/en/language.oop5.decon.php

通常,在CI中不需要调用构造函数,除非您实际上想要一个构造函数.在您发布的示例中,代码在类的每个实例上加载辅助程序-与在每种方法中加载辅助程序相同,只是节省了大量键入并确保不会忘记它.您也可以将要加载的库/帮助程序/模型放入相应的自动加载数组中的config/autoload.php中(在CI手册中选中自动加载")

Usually, in CI is not necessary to call a constructor, unless you actually want one. In the example you posted, the code loads the helper on every instantiation of the class - which is the same as loading the helper in every method, just saves a lot of typing and ensures it's not forgotten. You can alternatively put the library/helper/model you want to have alywas loaded in the respective autoload array in config/autoload.php (check "autoloading" in CI's manual)

一旦在子Controller中定义了一个构造函数,您就不得不调用(邮件CI_Controller类的)父构造函数,因为在那里创建了主要CI对象,并加载了所有类,而您需要这些在您的孩子控制器中;如果这样做失败,则您的子类将单独构造并且不会继承.

Once you define a constructor in your child Controller you're compelled to call the parent constructor (of the mail CI_Controller class), because there is where the main CI object is created and all the classes are loaded, and you need those in your child controller too; if fail to do so your child class will construct separately and won't inherit.

我希望我能说清楚自己,英语不是我的母语:)

I hope I made myself clear, english is not my mothertongue :)

这篇关于CodeIgniter控制器构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆