当控制器类扩展父控制器时,为什么还需要父构造函数? [英] why do we still need parent constructor when controller class extends a parent controller?
问题描述
我是CodeIgniter和OOP的初学者。我正在阅读CI教程页面此处。我发现了一些在我脑海中提出问题的东西。
看看这段代码:
I'm a beginner in CodeIgniter and OOP. I was reading a page of CI tutorial here. I found something that made a question in my mind.
Look at this code:
<?php
class News extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('news_model');
}
我认为如果我们创建了一个扩展CI_Controller的类,我们认为它必须具有其父类中的所有方法和属性(虽然我们可以覆盖它们)。那么,为什么代码中有 parent :: __ construct();
?
I think if we made a class that extends CI_Controller, we assume it must have all methods and properties in its parent class (Although we can override them). So, why there is parent::__construct();
in the code?
推荐答案
__ construct()
是类的构造方法。如果您从中声明一个新的对象实例,它将运行。但是,它只运行自身的构造函数,而不是它的父元素。例如:
__construct()
is the constructor method of a class. It runs if you declare a new object instance from it. However, it only run the constructor of itself, not of its parent. For example:
<?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();
?>
在这种情况下,如果你需要在声明$ obj时运行A类的构造函数,那么你将会需要使用 parent :: __ construct()
:
In this case, if you need to run class A's constructor when $obj is declared, you'll need to use parent::__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();
?>
在CodeIgniter的情况下,该行运行CI_Controller中的构造函数。该构造函数方法应该以某种方式帮助您的控制器编码。而你只是想让它为你做好每一件事。
In CodeIgniter's case, that line runs the constructor in CI_Controller. That constructor method should have helped your controller codes in some way. And you'd just want it to do everythings for you.
这篇关于当控制器类扩展父控制器时,为什么还需要父构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!