萬盛學電腦網

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

PHP 物件導向程式設計完整指南:類別、封裝、繼承、介面與進階特性

類別定義與實例化

<?php
declare(strict_types=1);

class Person {
    // 屬性 (PHP 7.4+ 型別宣告)
    public string $name = 'NoName';
    protected int $age = 0;
    private string $idNumber = '';
    
    // 建構子
    public function __construct(string $name, int $age, string $idNumber) {
        $this->name = $name;
        $this->setAge($age);
        $this->idNumber = $idNumber;
    }
    
    // 方法
    public function greet(): string {
        return "Hello, I'm {$this->name}.";
    }
    
    // Getter/Setter (封裝)
    public function getAge(): int {
        return $this->age;
    }
    
    public function setAge(int $age): void {
        if ($age < 0 || $age > 150) {
            throw new InvalidArgumentException('年齡需在 0-150 之間');
        }
        $this->age = $age;
    }
    
    // 解構子
    public function __destruct() {
        // 清理資源、關閉連線等
    }
}

// 實例化
$person = new Person('Tom', 25, 'A123456789');
echo $person->greet(); // Hello, I'm Tom.
echo $person->getAge(); // 25
$person->setAge(26);

存取修飾詞與封裝

修飾詞類別內子類別外部用途
public✓✓✓公開 API
protected✓✓✗繼承體系共享
private✓✗✗內部實作細節

封裝優勢: 控制存取邏輯、驗證資料、隱藏實作、未來可變更內部儲存方式不影響外部介面。

靜態成員

繼承與多型

name = $name;
    }
    
    abstract public function makeSound(): string;
    
    public function introduce(): string {
        return "I'm {$this->name}, " . $this->makeSound();
    }
}

class Dog extends Animal {
    public function makeSound(): string {
        return 'Woof!';
    }
    
    public function fetch(): string {
        return "{$this->name} fetched the ball!";
    }
}

class Cat extends Animal {
    public function makeSound(): string {
        return 'Meow~';
    }
}

$animals = [new Dog('Buddy'), new Cat('Kitty')];
foreach ($animals as $animal) {
    echo $animal->introduce() . "\n";
}
// I'm Buddy, Woof!
// I'm Kitty, Meow~

介面

log("Creating user: $name");
        return new User($name);
    }
}

Trait 程式碼複用

updatedAt = new DateTime();
    }
}

class Article {
    use Timestampable;
    
    public function __construct() {
        $this->createdAt = new DateTime();
        $this->updatedAt = new DateTime();
    }
}

魔術方法

方法觸發時機常見用途
__construct()new 實例化初始化
__destruct()物件銷毀釋放資源
__call($name, $args)呼叫不存在的方法動態代理、委派
__callStatic($name, $args)靜態呼叫不存在方法工廠方法
__get($name)讀取不可見屬性虛擬屬性、資料映射
__set($name, $value)寫入不可見屬性驗證、觸發事件
__isset($name)isset($obj->prop)虛擬屬性存在性
__unset($name)unset($obj->prop)清理虛擬屬性
__toString()echo $obj物件字串表示
__invoke()$obj()可呼叫物件
__clone()clone $obj深層複製
__serialize()serialize() (PHP 7.4+)自訂序列化
__unserialize()unserialize() (PHP 7.4+)自訂反序列化

委派模式範例 (__call)

address = new Address();
    }
    
    // 委派給 Address
    public function __call(string $name, array $args): mixed {
        if (method_exists($this->address, $name)) {
            return $this->address->$name(...$args);
        }
        throw new BadMethodCallException("Method $name not found");
    }
    
    // 深層複製
    public function __clone(): void {
        $this->address = clone $this->address;
    }
}

$p = new Person();
$p->setCity('Taipei'); // 委派到 Address::setCity()
$p->setZip('100');
$p2 = clone $p;
$p2->setCity('Kaohsiung');
echo $p->getCity();  // Taipei (未受影響,深層複製)

匿名類別 (PHP 7+)

log('Anonymous class in action');

唯讀屬性 (PHP 8.1+)

 false]);
// $config->appName = 'Other'; // Error: Cannot modify readonly property

最佳實務總結

  1. 單一職責:一個類別只負責一件事
  2. 介面導向:依賴抽象而非具體實作
  3. 組合優於繼承:用 Trait/委派替代深層繼承
  4. 不可變物件:readonly 屬性、with 方法回傳新實例
  5. 嚴格型別:declare(strict_types=1) + 完整型別提示
  6. 靜態分析:PHPStan Level 5+、Psalm
  7. 測試導向:依賴注入、介面模擬
copyright © 萬盛學電腦網 all rights reserved