反射
ReflectionClass
- 獲取被包裝類的實例化對象
ReflectionClass::newInstance() - 獲取改類的屬性
ReflectionClass::getproperties() - 獲取註釋:
foreach (propertiesas property) {
if (property->isProtected()) { docblock = $property->getDocComment(); 獲取類的方法
getMethods() 來獲取到類的所有methods。
hasMethod(string) 是否存在某個方法
getMethod(string) 獲取方法
執行類的方法
$instance = ReflectionClass::newInstance(); $instance->fun1(); $method = $class->getmethod('getName'); // 獲取Person 類中的getName方法 $method->invoke($instance); // 執行getName 方法
- 獲取被包裝類的實例化對象
ReflectionMethod
- 是否“public”、“protected”、“private” 、“static”類型
- 方法的參數列表
- 方法的參數個數
- 反調用類的方法
- 最簡單的應用:
class test{
public function fun1($a,$b){
echo '$a is :'.$a.', $b is :'.$b."<br>";
}
}
$obj = new test;
$r = new ReflectionClass($obj);
//ReflectionClass的構造參數既可以是一個包含類名的字符串(string)也可以是一個對象(object)。
$method = $r->getMethod('fun1');
$method->invoke($obj,1,333);
//$method->invokeArgs($obj,[1,333]);
- 用法實例
<?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();
?>
可見,通過代理類ClassOneDelegator來代替ClassOne類來實現他的方法。
<?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();
?>