本文实例讲述了PHP反射实际应用。分享给大家供大家参考,具体如下:
1.自动生成文档
根据反射的分析类,接口,函数和方法的内部结构,方法和函数的参数,以及类的属性和方法,可以自动生成文档。
class Student
{
const NORMAL = 1;
const FORBIDDEN = 2;
/**
* 用户ID
* @var 类型
*/
public $id;
/**
* 获取id
* @return int
*/
public function getId()
{
return $this->id;
}
public function setId($id = 1)
{
$this->id = $id;
}
}
$ref = new ReflectionClass('Student');
$doc = $ref->getDocComment();
echo $ref->getName() . ':' . getComment($ref) , "
";
echo "属性列表:
";
printf("%-15s%-10s%-40s
", 'Name', 'Access', 'Comment');
$attr = $ref->getProperties();
foreach ($attr as $row) {
printf("%-15s%-10s%-40s
", $row->getName(), getAccess($row), getComment($row));
}
echo "常量列表:
";
printf("%-15s%-10s
", 'Name', 'Value');
$const = $ref->getConstants();
foreach ($const as $key => $val) {
printf("%-15s%-10s
", $key, $val);
}
echo "
";
echo "方法列表
";
printf("%-15s%-10s%-30s%-40s
",