大型項目中模塊耦合導致牽一髮動全身。OOP 通過封裝 (隱藏內部細節)、繼承 (復用擴展)、多態 (統一介面不同實現) 降低耦合,提高可維護性。
clone。__construct()、__destruct()。public/protected/private。<?php
namespace App\Model;
interface Loggable {
public function log(string $msg): void;
}
abstract class BaseModel implements Loggable {
protected int $id = 0;
protected array $data = [];
public function __construct(array $data = []) {
$this->data = $data;
}
public function __get(string $name) {
return $this->data[$name] ?? null;
}
public function __set(string $name, $value): void {
$this->data[$name] = $value;
}
public function __isset(string $name): bool {
return isset($this->data[$name]);
}
public function __unset(string $name): void {
unset($this->data[$name]);
}
abstract protected function save(): bool;
public function log(string $msg): void {
error_log("[{$this->class}] $msg");
}
}
final class User extends BaseModel {
public const STATUS_ACTIVE = 1;
public const STATUS_BANNED = 0;
private string $passwordHash = '';
public function setPassword(string $plain): void {
$this->passwordHash = password_hash($plain, PASSWORD_BCRYPT);
}
public function verifyPassword(string $plain): bool {
return password_verify($plain, $this->passwordHash);
}
protected function save(): bool {
// PDO 保存邏輯...
$this->log("User {$this->id} saved");
return true;
}
}
// 使用
$user = new User(['name' => 'Tom', 'email' => 'tom@example.com']);
$user->setPassword('secret123');
$user->save();
?>
| 方法 | 觸發時機 |
|---|---|
__construct | new 實例化 |
__destruct | 對象銷毀/腳本結束 |
__call | 調用不可訪問方法 |
__callStatic | 調用不可訪問靜態方法 |
__get | 讀取不可訪問屬性 |
__set | 寫入不可訪問屬性 |
__isset | isset() 檢測不可訪問屬性 |
__unset | unset() 刪除不可訪問屬性 |
__sleep | serialize() 前 |
__wakeup | unserialize() 後 |
__toString | 對象作字符串使用 |
__invoke | 對象作函數調用 |
__clone | clone 對象時 |
__debugInfo | var_dump() 時 |