PHP 單繼承限制導致無關類別無法共享通用功能。傳統方案:
Trait 提供水平代碼復用,無需繼承關係即可混入方法群。
<?php
// 定義 Trait
trait AddressTrait {
private $address;
public function getAddress() { return $this->address; }
public function setAddress($address) { $this->address = $address; }
}
// 使用 Trait
class Business {
use AddressTrait;
}
class Individual {
use AddressTrait;
}
class Order {
use AddressTrait;
}
// 三個無關類別都獲得地址功能
$biz = new Business();
$biz->setAddress('台北市信義路 100 號');
echo $biz->getAddress(); // 台北市信義路 100 號
<?php
// 繼承方案:強行建立關係
class Client {
private $address;
public function getAddress() { return $this->address; }
public function setAddress($addr) { $this->address = $addr; }
}
class Business extends Client { } // Business 是 Client?語意錯誤
class Order extends Client { } // Order 是 Client?更錯誤
// Trait 方案:純功能混入
trait Addressable { /* ... */ }
class Business { use Addressable; } // Business 有地址功能 ✓
class Order { use Addressable; } // Order 有地址功能 ✓
class User {
use Addressable, Loggable, Timestampable, Validatable;
}
use A, B {
B::method insteadof A; // 選 B 的 method
A::method as methodA; // 保留 A 的 method 別名
}
use SecretTrait {
secretMethod as protected; // 改為 protected
secretMethod as private mySecret; // 私有別名
}
trait Counter {
public static $count = 0;
public static function increment() { return ++self::$count; }
}
// 每個使用類擁有獨立的 $count 副本
考慮使用 Trait 當:
不適用當:
Trait 讓 PHP 突破單繼承限制,實現真正的橫向代碼復用,是現代 PHP 開發不可或缺的工具。