本文实例讲述了PHP反射。分享给大家供大家参考,具体如下:
name = $name;
$this->skills = $skills;
}
public function attack($hero) {
echo "Attack {$hero->name}" . PHP_EOL;
}
public function execute($index) {
echo "Axecute {$index} skill" . PHP_EOL;
}
}
$ref = new ReflectionClass('Hero');
if ($ref->isInstantiable()) {
echo '可以实例化' . PHP_EOL;
}
// 获取类的构造函数
$constructor = $ref->getConstructor();
print_r($constructor); //ReflectionMethod E对象
//获取属性
if ($ref->hasProperty('name')) {
$attr = $ref->getProperty('name');
print_r($attr); //ReflectionProperty 对象
}
// 获取属性列表
$attributes = $ref->getProperties();
foreach ($attributes as $row) {
//row 为 ReflectionProperty 的实例
echo $row->getName() . "n";
}
// 获取方法
if ($ref->hasMethod('attack')) {
$method = $ref->getMethod('attack');
//$method 为 ReflectionMethod 的实例
print_r($method);
}
// 获取方法列表
$methods = $ref->getMethods();
foreach ($methods as $row) {
//这的row 是 ReflectionMethod 的实例
echo $row->getName() . PHP_EOL;
}
牋 [class] => Hero
)
ReflectionProperty Object
(
牋 [name] => name
牋 [class] => Hero
)
name
skills
ReflectionMethod Object
(
牋 [name] => attack
牋 [class] => Hero
)
__construct
attack
executephp面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。

