PHP 透過 public、protected、private 三大關鍵字實現封裝。本文通過實戰代碼演示三者差異、存取規則、動態屬性操作與現代封裝最佳實踐。
<?php
class People {
private $name = "li ming";
}
$p = new People();
// ❌ 致命錯誤:Cannot access private property People::$name
echo $p->name;
?>
<?php
class People {
private string $name = "li ming";
// 受控讀取
public function getName(): string {
return $this->name;
}
// 受控寫入(可加驗證)
public function setName(string $name): void {
if (strlen($name) < 2) {
throw new InvalidArgumentException("名稱過短");
}
$this->name = $name;
}
}
$p = new People();
echo $p->getName(); // li ming
$p->setName("Wang"); // 成功
// $p->setName("A"); // 拋出異常
?>
未聲明可見性的屬性/方法隱含 public(不推薦隱式,建議显式聲明)。
<?php
class Man {
public string $name = "John";
public int $age = 20; // 显式型別 (PHP 7.4+)
}
$a = new Man();
echo $a->name . "<br>"; // John
echo $a->age . "<br>"; // 20
// 外部可隨意修改
$a->name = "Tom";
$a->age = 25;
$a->newProp = "動態屬性"; // 動態新增屬性(不推薦)
echo $a->name . "<br>"; // Tom
?>
<?php
class Legacy {
var $oldStyle = "PHP 4 風格"; // 等同於 public
}
?>
現代代碼禁用 var,統一使用 public。
<?php
class Man {
public string $name = "John";
}
$a = new Man();
$a->name = "Tom"; // 修改既有屬性
$a->age = 20; // 動態新增屬性(PHP 8.2+ 棄用警告)
$a->{'custom-key'} = "值"; // 特殊鍵名
echo $a->name . "<br>"; // Tom
echo $a->age . "<br>"; // 20
?>
<?php
// PHP 8.2+ 會拋出 Deprecated: Creation of dynamic property
// 解決方案:
// 1. 宣告所有屬性
// 2. 使用 #[AllowDynamicProperties] 屬性(極少數合法場景)
// 3. 改用陣列/Map 儲存動態資料
#[AllowDynamicProperties]
class FlexibleEntity {
private array $data = [];
public function __set(string $name, $value) {
$this->data[$name] = $value;
}
public function __get(string $name) {
return $this->data[$name] ?? null;
}
}
?>
<?php
class Base {
protected string $secret = "base secret";
protected function internalLogic(): string {
return "base logic";
}
}
class Derived extends Base {
public function reveal(): string {
return $this->secret . " | " . $this->internalLogic(); // ✅ 可訪問
}
}
$d = new Derived();
echo $d->reveal(); // base secret | base logic
// $d->secret; // ❌ 外部不可訪問
?>
<?php
class Encapsulated {
private array $data = [];
private array $allowed = ['name', 'email', 'age'];
public function __set(string $name, $value): void {
if (!in_array($name, $this->allowed)) {
throw new Exception("屬性 $name 不允許設置");
}
// 類型驗證、清理、日誌...
$this->data[$name] = $value;
}
public function __get(string $name) {
if (!in_array($name, $this->allowed)) {
throw new Exception("屬性 $name 不存在");
}
return $this->data[$name] ?? null;
}
public function __isset(string $name): bool {
return isset($this->data[$name]);
}
public function __unset(string $name): void {
unset($this->data[$name]);
}
}
$user = new Encapsulated();
$user->name = "Alice"; // 觸發 __set
echo $user->name; // 觸發 __get
isset($user->email); // 觸發 __isset
unset($user->age); // 觸發 __unset
?>
<?php
class ImmutableDTO {
public readonly string $id;
public readonly string $email;
public readonly \DateTimeImmutable $createdAt;
public function __construct(string $id, string $email) {
$this->id = $id;
$this->email = $email;
$this->createdAt = new \DateTimeImmutable();
}
}
$dto = new ImmutableDTO('123', 'a@b.com');
// $dto->email = 'new'; // ❌ Error: Cannot modify readonly property
?>
| 場景 | 推薦可見性 | 理由 |
|---|---|---|
| 資料庫欄位映射 | private + getter/setter | 驗證、轉換、延遲載入 |
| 配置常數 | public const | 不可變、編譯期已知 |
| 子類需自定義演算法 | protected 方法 | 模板方法模式 |
| 子類需調整業務參數 | protected 屬性 | 如利潤率、閾值常數 |
| DTO/值物件 | public readonly | 不可變、無行為、純資料 |
| 服務類依賴 | private + 構造注入 | 不可變依賴、易測試 |
| 快取/計數器 | private static | 類別級共享狀態 |
<?php
class Secret {
private string $token = "hidden";
}
$reflection = new ReflectionClass(Secret::class);
$property = $reflection->getProperty('token');
$property->setAccessible(true); // 繞過 private
$obj = new Secret();
echo $property->getValue($obj); // hidden
?>
警告:業務代碼嚴禁使用反射繞過封裝,僅限測試、序列化庫、ORM 框架內部。
readonly、#[AllowDynamicProperties]、型別提示、靜態分析強化封裝良好的封裝不是「藏起來」,而是「定義清晰的邊界與協議」。以語義邊界替代資料邊界,讓類別成為可靠的業務抽象單元。