面向對象的特性:繼承性

1、繼承與擴展函數

1.子類使用extends繼承父類,子類能夠將父類全部內容繼承,以下:
//多層繼承
    class Person {
        var $name;
        var $age;
        var $sex;
        function __construct(){
            
        }
        function say(){
            
        }
        function eat(){
            echo "1111";
        }
        function run(){
            
        }
    };
    class Student extends Person {
        var $school;
        function __construct(){
            
        }
        function study(){
            
        }
    };
    class Teacher extends Student {
        var $gz;
        function teach(){
            
        }
    };
    $stu=new Student;
    $stu->eat();
    /1111

2.private沒法繼承給子類,以下:this

class Person {
        private $name="liu";
        var $age;
        var $sex;
        function __construct(){
            
        }
        function say(){
            echo $this->name;
        }
        function eat(){
            echo "1111";
        }
        function run(){
            
        }
    };
    class Student extends Person {
        var $school;
        function __construct(){
            
        }
        function study(){
            
        }
    };
    class Teacher extends Student {
        var $dw;
        function teach(){
            echo $this->name;
        }
    };
    $teacher=new Teacher;
    $teacher->say();//liu 只是子類引用繼承了父類的say()
    $teacher->teach();//error

3.protected保護權限,只能本身和子類使用,外部沒法讀取,以下:spa

class Person {
        private $name="liu";
        protected $age=10;
        var $sex;
        function __construct(){
            
        }
        function say(){
            echo $this->age;
        }
        function eat(){
            echo "1111";
        }
        function run(){
            
        }
    };
    class Student extends Person {
        var $school;
        function __construct(){
            
        }
        function study(){
            
        }
    };
    class Teacher extends Student {
        var $dw;
        function teach(){
            echo $this->age;
        }
    };
    $teacher=new Teacher;
    $teacher->say();//10
    $teacher->teach();//10

4.public(默認)公開權限,全部位置均可用,再也不重複舉例,各權限以下圖:
圖片描述code

2、繼承中的重載/覆蓋blog

1.強類型語言中重載:方法名相同,參數或參數個數不一樣
2.弱類型語言理解爲覆蓋:同一類中同名方法後覆蓋前
3.弱類型中的重載:子類裏能夠寫與父類同名的方法,即方法的擴展(接口、多態)
4.調用類的方法Person::say();
5.調用父類(被覆蓋)的方法(默認關鍵字)parent::say();
6.__construct()也能夠覆蓋,但最開始必須調用父類構造函數,以下:
function __construct($name,$age,$sex,$school){
            //先調用父類構造方法,不然父類初始化後,子類不變
            parent::__construct($name,$age,$sex);
            $this->school=$school;
        }
7.權限:子類權限只能>=父類權限,即public > protected > private
相關文章
相關標籤/搜索