PHP 5 引入 Reflection API,提供類別、介面、函式、方法、參數、屬性、擴充套件等的運行時檢查能力,廣泛用於框架自動載入、依賴注入、文件生成、單元測試模擬等。
class Reflection { }
interface Reflector { }
class ReflectionException extends Exception { }
class ReflectionFunction implements Reflector { }
class ReflectionParameter implements Reflector { }
class ReflectionMethod extends ReflectionFunction { }
class ReflectionClass implements Reflector { }
class ReflectionObject extends ReflectionClass { }
class ReflectionProperty implements Reflector { }
class ReflectionExtension implements Reflector { }
export(Reflector $r, bool $return = false):匯出詳細資訊getModifierNames(int $modifiers):取得修飾詞名稱陣列getName()、isInternal()、isUserDefined()getFileName()、getStartLine()、getEndLine()getDocComment():取得 PHPDoc 註解getParameters():取得 ReflectionParameter 陣列invoke()、invokeArgs():動態呼叫getName()、isPassedByReference()、getClass()isArray()、allowsNull()、isOptional()、isDefaultValueAvailable()、getDefaultValue()getName()、isInternal()、isUserDefined()、isInstantiable()hasConstant()、hasMethod()、hasProperty()getConstants()、getMethods()、getProperties()getConstructor()、getParentClass()、getInterfaces()newInstance()、newInstanceArgs()、newInstanceWithoutConstructor()class Container {
public function make($class) {
$ref = new ReflectionClass($class);
$constructor = $ref->getConstructor();
if (!$constructor) return $ref->newInstance();
$params = $constructor->getParameters();
$args = [];
foreach ($params as $param) {
$type = $param->getClass();
if ($type) {
$args[] = $this->make($type->name); // 遞迴解析
} elseif ($param->isDefaultValueAvailable()) {
$args[] = $param->getDefaultValue();
} else {
throw new Exception("無法解析參數 {$param->getName()}");
}
}
return $ref->newInstanceArgs($args);
}
}
setAccessible(true) 才能存取。ReflectionAttribute 支援屬性(Attribute)反射。