LoginSignup
2
1

More than 3 years have passed since last update.

PHP classの継承(オーバーライド)について

Last updated at Posted at 2021-05-10

CakePHPを使用していて継承を使いたくなった時のメモ

参考記事:https://www.atmarkit.co.jp/ait/articles/1508/05/news021.html

結論

オーバーライドは継承元のメソッドがpublicでもprotected でも可能

検証例1

<?php 


class hoge {
    protected function A() {
        echo "hoge's Aを呼びます\n";
    }
//
public $i_ = 1;
}
//
class foo extends hoge {
    public function A() {
        echo "foo's Aを呼びます\n";
    }
//
public $i_ = 999;
}

// class fooを使う
$foo_obj = new foo();
$foo_obj->A();
var_dump($foo_obj);

結果
/*foo's Aを呼びます
object(foo)#1 (1) {
  ["i_"]=>
  int(999)
}*/

上記例では継承元hogeクラスのprotectedメソッド A()を子クラスfooでオーバーライドしている。

検証例2
親クラスのオーバーライドをした時に親クラスの元のメソッドも呼びたい場合
parent::メソッド名()を使用する

<?php 


class hoge {
    protected function A() {
        echo "hoge's Aを呼びます\n";
    }
}
//
class foo extends hoge {
    public function A() {
        echo "foo's Aを呼びます\n";
        parent::A();
    }
}

// class fooを使う
$foo_obj = new foo();
$foo_obj->A();

結果
/*
foo's Aを呼びます
hoge's Aを呼びます
*/
2
1
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
2
1