从PHP中的父类继承时,特别是在Codeigniter中parent::__construct or parent::model()
做了什么?
如果我不是__construct
父母班,它会有什么不同?并且,建议采用哪种方式?
-添加-
Codeigniter更多地关注Codeigniter,具体parent::__construct
取决于版本的不同方式的调用,如果Codeigniter自动执行此操作,可以省略.
gio*_*gio 75
这是一个普通的类构造函数.我们来看下面的例子:
class A {
protected $some_var;
function __construct() {
$this->some_var = 'value added in class A';
}
function echo_some_var() {
echo $this->some_var;
}
}
class B extends A {
function __construct() {
$this->some_var = 'value added in class B';
}
}
$a = new A;
$a->echo_some_var(); // will print out 'value added in class A'
$b = new B;
$b->echo_some_var(); // will print out 'value added in class B'
Run Code Online (Sandbox Code Playgroud)
如你所见,B类继承了A中的所有值和函数.所以类成员$some_var
可以从A和B中访问.因为我们在B类中添加了一个构造函数,所以当你使用A类的构造函数时正在创建一个B类的新对象.
现在看下面的例子:
class C extends A {
// empty
}
$c = new C;
$c->echo_some_var(); // will print out 'value added in class A'
Run Code Online (Sandbox Code Playgroud)
如您所见,因为我们尚未声明构造函数,所以隐式使用类A的构造函数.但我们也可以做以下,相当于C类:
class D extends A {
function __construct() {
parent::__construct();
}
}
$d = new D;
$d->echo_some_var(); // will print out 'value added in class A'
Run Code Online (Sandbox Code Playgroud)
因此,parent::__construct();
当您希望子类中的构造函数执行某些操作时,您只需使用该行,并执行父构造函数.给出的例子:
class E extends A {
private $some_other_var;
function __construct() {
// first do something important
$this->some_other_var = 'some other value';
// then execute the parent constructor anyway
parent::__construct();
}
}
Run Code Online (Sandbox Code Playgroud)
更多信息可以在这里找到:http://php.net/manual/en/language.oop5.php