当控制器类扩展父控制器时,为什么还需要父构造函数?

Moh*_*eri 9 php inheritance codeigniter class

我是CodeIgniter和OOP的初学者.我读CI教程的页面在这里.我发现了一些在我脑海中提出问题的东西.
看看这段代码:

<?php
class News extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->model('news_model');
    }
Run Code Online (Sandbox Code Playgroud)

我想如果我们创建了一个扩展CI_Controller的类,我们假设它必须在其父类中具有所有方法和属性(尽管我们可以覆盖它们).那么,为什么parent::__construct();代码中有?

Koa*_*ung 12

__construct()是类的构造方法.如果您从中声明一个新的对象实例,它将运行.但是,它只运行自身的构造函数,而不是它的父元素.例如:

<?php

class A {
  public function __construct() {
    echo "run A's constructor\n";
  }
}

class B extends A {
  public function __construct() {
    echo "run B's constructor\n";
  }
}

// only B's constructor is invoked
// show "run B's constructor\n" only
$obj = new B();

?>
Run Code Online (Sandbox Code Playgroud)

在这种情况下,如果在声明$ obj时需要运行A类的构造函数,则需要使用__construct():

<?php

class A {
  public function __construct() {
    echo "run A's constructor\n";
  }
}

class B extends A {
  public function __construct() {
    parent::__construct();
    echo "run B's constructor\n";
  }
}

// both constructors of A and B are invoked
// 1. show "run A's constructor\n"
// 2. show "run B's constructor\n"
$obj = new B();

?>
Run Code Online (Sandbox Code Playgroud)

在CodeIgniter的情况下,该行在CI_Controller中运行构造函数.该构造函数方法应该以某种方式帮助您的控制器编码.而你只是想让它为你做每件事.