这是一个普通的类构造函数。让我们看一下下面的例子:
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'
如您所见,类 B 从 A 继承所有值和函数。因此,可以从 A 和 B 访问类成员。由于我们在类 B 中添加了一个构造函数,因此在创建类 B 的新对象时,将不使用类 A 的构造函数。$some_var
现在看一下以下示例:
class C extends A {
// empty
}
$c = new C;
$c->echo_some_var(); // will print out 'value added in class A'
如您所见,因为我们尚未声明构造函数,所以隐式使用类 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'
因此,仅当您希望子类中的构造函数执行某些操作并执行父构造函数时,才需要使用该行。给出的示例: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();
}
}
更多信息可以在这里找到:http://php.net/manual/en/language.oop5.php