OOP 讓代碼模組化、可複用、易維護。PHP 5+ 確立了完整物件模型。本文以「人」與「矩形」為例,手把手構建類別、實例化物件、掌握 `$this`、構造/解構函數與封裝精髓。
<?php
class Person {
public $name; public $sex; public $age; // 屬性 (PHP 5+ 建議用 public/protected/private)
public function say() { echo "我是 {$this->name},{$this->age} 歲。"; }
public function run() { echo "{$this->name} 在跑步。"; }
}
$p1 = new Person(); $p1->name="張三"; $p1->sex="男"; $p1->age=20;
$p2 = new Person(); $p2->name="李四"; $p2->sex="女"; $p2->age=30;
$p1->say(); // 我是張三,20歲。
$p2->run(); // 李四在跑步。
?>
方法內部用 `$this->property`、`$this->method()` 存取自身成員。外部用 `$obj->member`。
<?php
class Person {
public $name; public $sex; public $age;
public function __construct($name, $sex, $age) {
$this->name=$name; $this->sex=$sex; $this->age=$age;
}
public function say() { echo "我是 {$this->name},{$this->age} 歲。"; }
}
$p1 = new Person("張三","男",20); // 一行完成建立+賦值
$p1->say();
?>
public function __destruct() { echo "再見,{$this->name}。"; }
物件無引用或腳本結束前自動觸發,用於關閉連線、釋放資源、寫日誌。
<?php
class Person {
private $name; private $sex; private $age; // 僅內部可見
private $salary; // 隱私薪資
public function __construct($name, $sex, $age, $salary) {
$this->name=$name; $this->sex=$sex; $this->age=$age; $this->salary=$salary;
}
// 對外可控介面 (Getter/Setter)
public function getName() { return $this->name; }
public function setAge($age) { if($age>0 && $age<150) $this->age=$age; }
public function getSalary() { return "保密"; } // 完全屏蔽
public function say() { echo "我是 {$this->name}。"; }
}
$p = new Person("王五","男",25,50000);
echo $p->getName(); // 王五
$p->setAge(26); // 合法修改
$p->setAge(-5); // 被攔截
echo $p->getSalary(); // 保密
// echo $p->salary; // Fatal Error: Cannot access private property
?>
| 關鍵字 | 類內部 | 子類別 | 外部 |
|---|---|---|---|
| public | ✓ | ✓ | ✓ |
| protected | ✓ | ✓ | ✗ |
| private | ✓ | ✗ | ✗ |
class Student extends Person {
public $school;
public function __construct($name,$sex,$age,$school) {
parent::__construct($name,$sex,$age); // 呼叫父構造
$this->school=$school;
}
public function say() { // 覆寫 (Override)
parent::say(); echo " 就讀於 {$this->school}。";
}
}
$s = new Student("小明","男",18,"第一高中");
$s->say(); // 我是小明,18歲。就讀於第一高中。
掌握類別定義、實例化、構造/解構、封裝、繼承五大支柱,即踏入 PHP OOP 大門,準備好迎接介面、Trait、設計模式的進階之旅。