PHP 5 的反射 API(Reflection API)提供了在執行時檢查類別、介面、方法與屬性的能力。本文透過兩個完整範例,示範如何利用反射機制實現動態代理模式,將方法呼叫委派給目標物件。
<?php
class ClassOne {
function callClassOne() {
print "In Class One";
}
}
class ClassOneDelegator {
private $targets;
function __construct() {
$this->target[] = new ClassOne();
}
function __call($name, $args) {
foreach ($this->target as $obj) {
$r = new ReflectionClass($obj);
if ($method = $r->getMethod($name)) {
if ($method->isPublic() && !$method->isAbstract()) {
return $method->invoke($obj, $args);
}
}
}
}
}
$obj = new ClassOneDelegator();
$obj->callClassOne(); // 輸出:In Class One
?>
<?php
class ClassOne {
function callClassOne() {
print "In Class One";
}
}
class ClassOneDelegator {
private $targets;
function addObject($obj) {
$this->target[] = $obj;
}
function __call($name, $args) {
foreach ($this->target as $obj) {
$r = new ReflectionClass($obj);
if ($method = $r->getMethod($name)) {
if ($method->isPublic() && !$method->isAbstract()) {
return $method->invoke($obj, $args);
}
}
}
}
}
$obj = new ClassOneDelegator();
$obj->addObject(new ClassOne());
$obj->callClassOne(); // 輸出:In Class One
?>
反射操作較一般方法呼叫有額外開銷,高頻率呼叫場景建議快取反射物件或採用代碼生成方式優化。