PHP OOP
類跟對象的關系 類是對象的抽象(對象的描述(屬性),對象的行為(方法)) 對象是類的實體 面相對象的三大特征:封裝、集成、多態 自定義類 Class?Person{ } 屬性定義 屬性是類里面的成員,所以要定義屬性的前提條件是需要聲明一個類 Class?Person{ public?$name;//?屬性 public?$age; public?$sex; } 方法定義 方法是定義特定功能的代碼塊,在類中定義方法表示,創建對象之后,對象的特定行為; Class?Person{ public?function?eat($food){ echo?"Person?can?eat?".$food; } } 實例化對象 Class?Person{ public?$name;//?屬性 public?$age; public?$sex; public?function?eat($food){ echo?"Person?can?eat?".$food; } } $person1=new?Person(); 屬性的賦值 $person1->name="curtis"; echo?$person1->name; 類方法的調用 $person1->eat("Apple"); 繼承(PHP是單繼承,也就是一個子類只能有一個父類) 為什么要繼承? 回復:為了屬性、方法的重復利用; 業務場景: 有個Person類,有一個Student類; Person里面有姓名、年齡、性別 如果Student里面再將上面的屬性定義一次,那就糟蹋了繼承這個神器; Person類叫Student類的父類,Student類是Person類的之類; Class?Person{ public?$name;//?屬性 public?$age; public?$sex; public?function?eat($food){ echo?"can?eat?".$food; } } Class?Student?extends?Person{ public?$student_id; public?function?write(){ echo?"I?can?write"; } public?function?read(){ echo?"I?can?read"; } } $student1=new?Student(); $student1->name="curtis1"; echo?$student1->name; echo?"<br?/>"; $student1->eat("面"); echo?"<br?/>"; 訪問修飾符 public?protected?private public?當前類,子類中均可訪問; protected?當前類,子類內部允許訪問; private?當前類內部允許訪問; 這個地方需要重點了解: 范圍 什么叫類內部? {}內叫類內部,出了{},實例化對象的時候構造函數也是內內部; Class?Person{ public?$name;//?屬性 public?$age; private?$sex;//?私有屬性 public?function?eat($food){ echo?"eat?".$food; } function?__construct($sex){ echo?"性別:".$sex; } } Class?Student?extends?Person{ public?$student_id; public?function?write(){ echo?"I?can?write"; } public?function?read(){ echo?"I?can?read"; } } $person1=new?Person("男"); static?關鍵字 為什么要有這么一個關鍵字? 常量 PI 靜態屬性?public?static?$PI?=?3.14; 靜態方法? 靜態成員訪問方式(類外部): 類名::屬性名稱 在當前類中訪問靜態屬性: statis::屬性名; 在子類內部訪問父類靜態成員,parent::屬性名;statis::屬性名; class?Person { public?$name; //?屬性 public?$age; private?$sex; //?私有屬性 public?function?eat($food) { echo?"eat?"?.?$food; } public?static?$PI?=?3.14; /** *?構造函數 */ function?__construct($sex) { echo?"性別:"?.?$sex; } function?show(){ echo?static::$PI; } } class?Student?extends?Person { public?$student_id; public?function?write() { echo?"I?can?write"; } function?__construct() {} public?function?read() { echo?"I?can?read"; } public?function?add() { echo?1?+?parent::$PI."<br?/>"; echo?2?+?static::$PI; } } $person1?=?new?Person("男"); echo?"<br?/>"; $person1->show(); echo?"<br?/>"; echo?Person::$PI?.?"<br?/>"; $student1?=?new?Student(); echo?Student::$PI; echo?"<br?/>"; $student1->add(); 方法的重寫 方法的重載 什么叫相同的方法,什么叫不同的方法? 回復:相同的方法:方法名稱相同,方法的參數列表相同; 不同的方法:方法名稱不同;方法名稱相同,方法的參數列表不同; 為什么會有方法的重寫? 回復:父類定義的方法子類有同樣的方法,子類的中的方法要實現有自己的行為; 方法的重載 為什么會有方法的重載? 回復:類中同樣一個方法名稱,通過不同的參數傳遞實現各自的行為; final關鍵字 跟方法的重寫對應來的 父類中有一個final關鍵字修飾的方法,子類想對該方法進行重寫那是不被允許的; 接口(interface)
轉載于:https://www.cnblogs.com/meroselove/p/5275318.html
總結
- 上一篇: Geometric Shapes - P
- 下一篇: jquery-11 如何制作鼠标右键菜单