萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 面向對象編程(OOP)核心概念與實戰入門

為什麼選擇 OOP?

  • 封裝: 數據與行為綁定,隱藏內部實現,暴露穩定接口。
  • 繼承: 代碼復用,建立「是一種」關係,子類擴展父類功能。
  • 多態: 同一接口不同實現,運行時動態綁定,提升靈活性。
  • 模塊化協作: 適合團隊並行開發,職責清晰,易於維護擴展。

類與對象基礎語法

<?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

三大特性深度解析

1. 封裝:訪問控制與數據保護

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,通過公共方法控制業務邏輯驗證。

2. 繼承:extends 關鍵字

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:: 調用父類實現。

3. 多態:接口與類型提示

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:代碼復用的橫向組合

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
    // ...
}

魔術方法

方法觸發時機典型用途
__constructnew 實例化初始化依賴、屬性
__destruct對象銷毀/腳本結束釋放資源、關閉連接
__call調用不可訪問方法動態代理、方法欄位映射
__callStatic調用不可訪問靜態方法靜態工廠、鏈式調用
__get/__set讀寫不可訪問屬性屬性代理、懶加載
__toString對象作為字符串使用調試輸出、模板渲染
__invoke對象作為函數調用可調用對象、閉包替代
__cloneclone 關鍵字複製對象深拷貝、重置標識
__serialize/__unserializePHP 7.4+ 序列化自定義序列化數據

介面 vs 抽象類

  • Interface: 定義契約,支持多實現,類可實現多個接口。PHP 8.0+ 支持默認方法實現。
  • Abstract Class: 提供部分基礎實現,包含狀態(屬性),單繼承。
  • 選擇: 「能做什麼」用 Interface,「是什麼」用 Abstract Class。

現代 PHP 開發規範 (PSR-12 風格)

<?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 代碼。

copyright © 萬盛學電腦網 all rights reserved