結論
- 子クラスの__construct()が親クラスの__construct()をオーバーライドしているのが原因。
- parent::__construct();を子クラスの__construct()に書けばおk
事象
内容
以下のように親クラス、子クラスどちらにも__construct()がある場合、
そのままだと親クラスの__construct()が読み込まれない。
<?php
class ParentClass {
public function __construct() {
define('SOMETHING',"this is something.");
}
}
class ChildClass extends ParentClass {
public function __construct() {
define('OTHERTHING',"this is otherthing.");
}
public function exec() {
echo SOMETHING;
echo "\n";
echo OTHERTHING;
}
}
$Child = new ChildClass();
$Child->exec();
期待する結果
this is something.
this is otherthing.
実際の結果
this is something.
原因
親クラスの__construct()を子クラスの__construct()がオーバーライドしたことで、
親クラスの__construct()が打ち消されてしまっている。
対処法
以下のように明示的に親クラスの__construct()を呼び出す必要がある。
parent::__construct()
変更後
<?php
class ParentClass {
public function __construct() {
define('SOMETHING',"this is something.");
}
}
class ChildClass extends ParentClass {
public function __construct() {
parent::__construct();
define('OTHERTHING',"this is otherthing.");
}
public function exec() {
echo SOMETHING;
echo "\n";
echo OTHERTHING;
}
}
$Child = new ChildClass();
$Child->exec();
結果
this is something.
this is otherthing.