圧倒的備忘録

忘却は罪である。

【PHP入門】クラスの継承について

extends

クラスのメンバを他のクラスで継承するメソッド

extendsの使い方

class クラス名 extends 継承元クラス名 {
    処理
}

注意点

親クラスでprivate修飾子による権限が指定されている場合は、そのメンバを引き継ぐことはできない。

サンプル

<?php

class ParentClass{
 
    public function workItem1($str){
        echo $str.'ParentClass <br>';
    }
 
    public function workItem2(){
        echo 'Processing of workItem2 of ParentClass. <br>';
    }
 
}
 
class ChildClass extends ParentClass{
 
    public function workItem1($str){
        echo $str.'ChildClass <br>';
    }
 
}
 
//インスタンスを生成
$parent = new ParentClass();
$child = new ChildClass();
 
//メソッドの呼出し
$parent->workItem1('Processing of ');
$child->workItem1('Processing of ');
 
$parent->workItem2();
$child->workItem2();
?>

実行結果

Processing of ParentClass 
Processing of ChildClass 
Processing of workItem2 of ParentClass. 
Processing of workItem2 of ParentClass.