1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?