【问题标题】:Codeigniter 2 difference between index and __construct and what to put in __constructCodeigniter 2 index和__construct之间的区别以及__construct中的内容
【发布时间】:2013-05-17 11:04:51
【问题描述】:

__construct 何时调用,index 何时调用?还有其他区别吗?

__construct 中应该放什么?什么是最佳做法,我应该把 $this->load 调用...?还有什么?

class Site extends CI_Controller {

      public function __construct() {

          parent::__construct();
          echo 'Hello World2';

     }

     public function index() {

          echo 'Hello World1';

     }
}

【问题讨论】:

    标签: php codeigniter controller construct


    【解决方案1】:

    __construct()先被调用,然后根据URL调用index()或其他函数。

    公共函数 __construct() 应包含:

    1. 分配整个班级使用的资源。 $this->加载
    2. 检查用户身份验证(如果整个班级都需要)

    公共函数 index() 应包含:

    1. 分配仅用于此函数的资源
    2. 调用视图或显示任何内容

    如果 public function __construct() 包含:

    1. 显示任何内容
    2. 任何代码只需要一个函数。

    【讨论】:

    • ^ 构造不仅在 index() 方法之前调用,而且在该控制器的所有其他方法之前调用。
    • @ThomasDavidPlat 感谢您的评论。英语不是我的母语,如何构造正确的句子,它将是先调用的构造函数?
    • 没关系 :) 它也不是我的母语。我会这样写:“__construct() 方法将在对象实例化期间执行,因此在执行该类的任何其他方法之前说”
    【解决方案2】:

    index() 将在您调用索引函数时执行,或者默认情况下,您可以说 index() 是一个默认函数......我们可以说 __construct() 是第一个方法,当通过其函数调用控制器时,它作为构造函数工作

    【讨论】:

      【解决方案3】:

      __construct 是类的constucter,而index() 是默认方法。

      假设你正在调用http://yoursite.com/,这相当于http://yoursite.com/your_default_controller/index

      这意味着,如果您的 URL 的第三段中没有任何内容,则默认调用该控制器的 index()。

      您可以在构造函数中初始化事物并加载视图和模型。

      您可以在 index() 处传递数据以查看

      【讨论】:

        【解决方案4】:

        假设你正在调用http://yoursite.com/,这相当于http://yoursite.com/your_default_controller/index

        index() 将在您调用index 函数时执行,或者默认情况下,您可以说index() 是一个默认函数......我们可以说__construct() 是第一个函数通过其函数调用控制器时的方法作为构造函数工作

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-07-22
          • 2016-10-22
          • 1970-01-01
          • 2017-12-11
          • 1970-01-01
          • 2011-06-05
          相关资源
          最近更新 更多