物件導向
在 OOP 的設計模式中,類別和介面扮演重要角色,讓我們可以遵守不重複原則(DRY)。
類別如同房屋的藍圖,所有物件都是照著類別建構的實際的房子。
物件透過 $this 關鍵字來參考自己。
Compare
| 類別(Class) | 抽象類別(Abstract Class) | 介面(Interface) | |
|---|---|---|---|
| 宣告屬性(attribute) | ✓ | ✓ | ✖ | 
| 常數(const) | ✓ | ✓ | ✓ | 
| 實例化(new class) | ✓ | ✖ | ✖ | 
| 抽象方法(abstract function) | ✖ | ✓ | ✓ | 
| 實作方法內容(functoin()) | ✓ | ✓ | ✖ | 
| 類別是否可繼承多個 | ✖ | ✖ | ✓ | 
copy from php 學習筆記
抽象類別:
- 若有抽象函式,繼承該類別後一定要實作。沒實作 error:
 
PHP Fatal error: Class Asian contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Person_abstractclass::eat)
- 抽象類別不能實例化
 
1  | abstract class Person_abstractclass{  | 
PHP Fatal error: Uncaught Error: Cannot instantiate abstract class Person_ab
- 在建構子裡 echo 沒有用,在實例化的時候不會被印出來
 - 祖先有繼承該類別,不管多遠古, if($obj instanceof animal)都會過(true)
 
介面
- 是一種特殊的抽象類別,所有方法都是抽象的,所以不能實作,且一樣:
- 不能實例化
 - 類別實現後一定要將全部方法都實作
 
 - 只有常數(const),沒有屬性
 - 可以繼承(extends)介面
 - 一個類別可以實現(implements)多個介面
 - 父類有實現介面, 子類就也一定要實現該介面
 
p.s. 介面和類別名稱不能相同
PHP Fatal error: Cannot declare class Person, because the name is already in use
類別
建構式
- 設置預設屬性值
 - 預載函式功能
 - 通常為了避免父子產生誤會,可以在子物件的建構式用以下的做法: 
1
2
3
4
5
6
7
8
9
10
11
12class demo extends CI_Controller(){
function __construct(){
parent::__construct();
$this->_init();
}
private function _init(){
//這才是真正寫建構式要預載功能的地方。
}
} 
清除
__destruct()