PHPにおけるクラスのオーバーライド
クラス
前回に引き続き今回もクラスについて記述していきたいと思います。
オーバーライド
派生クラスで基底クラス内のメソッド名と同じ名前を定義すると、
基底クラス側のメソッドは無視され、派生クラス側のメソッドの処理が実行されるようになります。
これは処理を上書きするということからオーバーライドと呼ばれています。
オーバーライドのサンプル
以下では基底クラスで定義した func1 というメソッドを派生クラス側で再定義してオーバーライドをしています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php class test{ public function func1(){ echo "test<br>" ; } } class test_hasei extends test{ public function func1(){ echo "test_hasei<br>" ; } } $obj = new test_hasei; $obj ->func1(); ?> |
結果は以下のように派生クラス側のメソッドの内容が実行されました。
基底クラス側のメソッドを実行したい場合
基底クラス側のメソッドを実行したい場合は
単純に基底クラスでインスタンス化すれば実行できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php class test{ public function func1(){ echo "test<br>" ; } } class test_hasei extends test{ public function func1(){ echo "test_hasei<br>" ; } } $obj = new test; $obj ->func1(); ?> |
privateアクセス修飾子を使用した場合
基底クラス側でprivateアクセス修飾子を使用したメソッドは
派生クラス側でオーバーライドすることができません。
以下では privateアクセス修飾子で定義していてもアクセスできるように
別メソッドを定義して $this でアクセスするようにしています。
publicアクセス修飾子を使用した場合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?php class test{ public function yobidashi(){ $this ->func1(); } public function func1(){ echo "test<br>" ; } } class test_hasei extends test{ public function func1(){ echo "test_hasei<br>" ; } } $obj = new test_hasei; $obj ->yobidashi(); ?> |
privateアクセス修飾子を使用した場合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?php class test{ public function yobidashi(){ $this ->func1(); } private function func1(){ echo "test<br>" ; } } class test_hasei extends test{ public function func1(){ echo "test_hasei<br>" ; } } $obj = new test_hasei; $obj ->yobidashi(); ?> |
結果は以下のようになります。