物件導向程式設計(Object-Oriented Programming,簡稱 OOP)是一種程式設計範式,也是軟體開發的重要方法論。它以「物件」為基本單位,將資料與操作資料的程式碼封裝在一起,顯著提升軟體的重用性、靈活性與擴展性。
在程式語言的三大範式中——面向過程、面向物件與函數式程式設計——面向物件屬於較高階的抽象思維。面向過程雖然也是抽象,但屬於基礎層面;面向物件則建立在面向過程之上,進行更高層次的抽象,因此理解難度相對較高。其核心思想包含:物件、封裝、可重用性與可擴展性。
在 PHP 中,類別使用 class 關鍵字定義,後接類別名稱與一對花括號,內含屬性(成員變數)與方法(成員函數)的定義:
class Person {
public $name;
public $gender;
public function say() {
echo $this->name . " is " . $this->gender;
}
}
透過 new 關鍵字建立類別的實例(物件),每個物件擁有屬於自己的屬性值:
$student = new Person();
$student->name = "Tom";
$student->gender = "male";
$student->say(); // 輸出:Tom is male
$teacher = new Person();
$teacher->name = "Kati";
$teacher->gender = "female";
$teacher->say(); // 輸出:Kati is female
這個過程展示了從抽象類別到具體物件的實例化。類別定義屬性與方法的結構,物件則持有具體的屬性值——正是因為 $student 與 $teacher 的姓名、性別不同,才能區分兩個不同的物件。
類別與物件的關係類似「服務與被服務」、「加工與被加工」,或是「原料與流水線」。只需在物件上呼叫類別中定義的方法,即可對屬性進行處理並展現功能。
print_r((array)$student);
var_dump($student);
序列化將物件轉為可儲存的字串格式:
$str = serialize($student);
echo $str;
file_put_contents('store.txt', $str);
輸出範例:O:6:"Person":2:{s:4:"name";s:3:"Tom";s:6:"gender";s:4:"male";}
反序列化還原物件:
$str = file_get_contents('store.txt');
$student = unserialize($str);
$student->say();