<?php
class User {
// 屬性可见性
public $name = 'Guest'; // 任意位置訪問
protected $role = 'user'; // 本類、子類、父類訪問
private $passwordHash = ''; // 僅本類訪問
// 靜態屬性(屬於類,不屬於實例)
public static $instanceCount = 0;
// 構造函數:實例化時自動調用
public function __construct(string $name = '') {
$this->name = $name ?: $this->name;
self::$instanceCount++;
}
// 方法
public function greet(): string {
return "Hello, {$this->name}!";
}
// 訪問器/修改器
public function setPassword(string $raw): void {
$this->passwordHash = password_hash($raw, PASSWORD_DEFAULT);
}
public function verifyPassword(string $raw): bool {
return password_verify($raw, $this->passwordHash);
}
// 靜態方法
public static function getCount(): int {
return self::$instanceCount;
}
// 析構函數:對象銷毀前調用
public function __destruct() {
self::$instanceCount--;
}
}
// 實例化
$user1 = new User('Alice');
$user2 = new User('Bob');
echo $user1->greet(); // Hello, Alice!
echo User::getCount(); // 2
// 訪問屬性
echo $user1->name; // Alice (public)
// echo $user1->passwordHash; // Fatal: Cannot access private property
class BankAccount {
private float $balance = 0.0;
public function deposit(float $amount): bool {
if ($amount <= 0) return false;
$this->balance += $amount;
return true;
}
public function withdraw(float $amount): bool {
if ($amount <= 0 || $amount > $this->balance) return false;
$this->balance -= $amount;
return true;
}
public function getBalance(): float {
return $this->balance;
}
}
原則: 屬性盡量 private,通過公共方法控制業務邏輯驗證。
abstract class Animal {
protected string $name;
public function __construct(string $name) {
$this->name = $name;
}
// 抽象方法:強制子類實現
abstract public function makeSound(): string;
// 普通方法可被繼承或重寫
public function introduce(): string {
return "我是 {$this->name}," . $this->makeSound();
}
}
class Dog extends Animal {
public function makeSound(): string {
return '汪汪汪~';
}
// 方法重寫
public function introduce(): string {
return parent::introduce() . ' 我會看家!';
}
}
$dog = new Dog('旺財');
echo $dog->introduce(); // 我是旺財,汪汪汪~ 我會看家!
關鍵字: final 禁止繼承/重寫;abstract 定義抽象類/方法;parent:: 調用父類實現。
interface Payable {
public function pay(float $amount): bool;
}
class Alipay implements Payable {
public function pay(float $amount): bool { /* ... */ return true; }
}
class WechatPay implements Payable {
public function pay(float $amount): bool { /* ... */ return true; }
}
// 依賴倒置:依賴抽象而非具體實現
class OrderService {
public function checkout(Payable $gateway, float $amount): bool {
return $gateway->pay($amount);
}
}
$service = new OrderService();
$service->checkout(new Alipay(), 100.00);
$service->checkout(new WechatPay(), 100.00);
trait Timestampable {
protected $createdAt;
protected $updatedAt;
public function setCreatedAt($time) { $this->createdAt = $time; }
public function getCreatedAt() { return $this->createdAt; }
}
trait SoftDeletes {
protected $deletedAt = null;
public function delete() { $this->deletedAt = new DateTime(); }
public function isDeleted() { return $this->deletedAt !== null; }
}
class Article {
use Timestampable, SoftDeletes; // 組合多個 Trait
// ...
}
| 方法 | 觸發時機 | 典型用途 |
|---|---|---|
__construct | new 實例化 | 初始化依賴、屬性 |
__destruct | 對象銷毀/腳本結束 | 釋放資源、關閉連接 |
__call | 調用不可訪問方法 | 動態代理、方法欄位映射 |
__callStatic | 調用不可訪問靜態方法 | 靜態工廠、鏈式調用 |
__get/__set | 讀寫不可訪問屬性 | 屬性代理、懶加載 |
__toString | 對象作為字符串使用 | 調試輸出、模板渲染 |
__invoke | 對象作為函數調用 | 可調用對象、閉包替代 |
__clone | clone 關鍵字複製對象 | 深拷貝、重置標識 |
__serialize/__unserialize | PHP 7.4+ 序列化 | 自定義序列化數據 |
<?php
declare(strict_types=1);
namespace App\Models;
use DateTimeImmutable;
use InvalidArgumentException;
final class User implements \JsonSerializable {
private string $id;
private string $email;
private DateTimeImmutable $createdAt;
public function __construct(string $email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException('Invalid email');
}
$this->id = bin2hex(random_bytes(16));
$this->email = $email;
$this->createdAt = new DateTimeImmutable();
}
public function getId(): string { return $this->id; }
public function getEmail(): string { return $this->email; }
public function getCreatedAt(): DateTimeImmutable { return $this->createdAt; }
public function jsonSerialize(): array {
return [
'id' => $this->id,
'email' => $this->email,
'created_at' => $this->createdAt->format(DATE_ATOM),
];
}
}
PHP OOP 從 PHP 5 起成熟,PHP 7/8 引入標量類型聲明、返回類型、屬性類型、聯合類型、match 表達式、readonly 屬性等現代特性。掌握封裝/繼承/多態三支柱,善用 Interface + Dependency Injection 解耦,配合 Composer + PSR-4 + 靜態分析,即可編寫可維護、可測試、可擴展的企業級 PHP 代碼。