PHP中的反射API[学习3]--检查方法
ReflectionClass 可以检查类,ReflectionMethod对象可以检查某个类中的方法。
获得ReflectionMethod对象有以下几种方法:
1:ReflectionClass::getMethods(); //获取所有方法的一个数组对象
2:ReflectionClass::getMethod($arg); //$arg类中的方法名
3:ReflectionMethod::__construct($class,$method)//$class 类, $method类中方法
代码:
<?php
require_once './oop.php';
//检查方法的属性
$methodData = function($class)
{
$details = '';
$name = $class -> getName(); //
if($class -> isUserDefined()){
$details .= "$name is user defined<br/>";
}
if($class -> isInternal()){
$details .= "$name is built-in<br/>";
}
if($class -> isAbstract()){
$details .= "$name is abstract<bt/>";
}
if($class -> isPublic()){
$details .= "$name is public<br/>";
}
if($class -> isPrivate()){
$details .= "$name is private<br />";
}
if($class -> isProtected()){
$details .= "$name is protected<br />";
}
if($class -> isStatic()){
$details .= "$name is static<br />";
}
if($class -> isFinal()){
$details .= "$name is final<br />";
}
if($class -> isConstructor()){
$details .= "$name is the isConstruct<br />";
}
if($class -> returnsReference()){
$details .="$name return a reference<br />";
}
return $details;
};
?>
使用ReflectionClass查看类方法具体调用代码:<?php
$model = new ReflectionClass('B');
print_r($mode -> getMethods()); // all method
//outprint
/**
Array
(
[0] => ReflectionMethod Object
(
[name] => __construct
[class] => B
)
[1] => ReflectionMethod Object
(
[name] => getName
[class] => B
)
[2] => ReflectionMethod Object
(
[name] => getAge
[class] => B
)
[3] => ReflectionMethod Object
(
[name] => getHeight
[class] => B
)
[4] => ReflectionMethod Object
(
[name] => mySelf
[class] => B
)
[5] => ReflectionMethod Object
(
[name] => returnA
[class] => B
)
)
*/
?>
具体某个方法代码如下:
<?php
//具体某个方法
$getName = $model -> getMethod('getName');
//outprint
//ReflectionMethod Object ( [name] => getName [class] => B )
?>
使用ReflectionMethod获取类方法:
<?php
$model = new ReflectionMethod('B', 'getName');
print_r($model);
//outprint
//ReflectionMethod Object ( [name] => getName [class] => B )
?>
具体输出方法的字符串信息可以参考学习2中的getClassSource方法,即输出该方法源代码。
有不足,不完全的地方还请看者指出,必当细心学习。

浙公网安备 33010602011771号