在例項化子項時呼叫父建構函式
子類的常見缺陷是,如果你的父級和子級都包含建構函式(__construct())方法,則只執行子類建構函式。在某些情況下,你可能需要從其子項執行父 __construct() 方法。如果你需要這樣做,那麼你將需要使用 parent:: 範圍解析器 :
parent::__construct();
現在在現實世界的情況下利用它看起來像:
class Foo {
function __construct($args) {
echo 'parent';
}
}
class Bar extends Foo {
function __construct($args) {
parent::__construct($args);
}
}
以上將執行父 __construct() 導致 echo 執行。