結論
- 子クラスの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.