LoginSignup
1
0

More than 5 years have passed since last update.

【PHP】extendsで親クラスの__constructメソッドが呼び出せていない場合の対処法

Posted at

結論

  • 子クラスの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.
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0