实例介绍PHP的Reflection反射机制
php5添加了一项新的功能:reflection。这个功能使得程序员可以reverse-engineer class, interface,function,method and extension。通过php代码,就可以得到某object的所有信息,并且可以和它交互。
假设有一个类person:
class person {
/**
* for the sake of demonstration, we"re setting this private
*/
private $_allowdynamicattributes = false;
/** type=primary_autoincrement */
protected $id = 0;
/** type=varchar length=255 null */
protected $name;
/** type=text null */
protected $biography;
public function getid()
{
return $this->id;
}
public function setid($v)
{
$this->id = $v;
}
public function getname()
{
return $this->name;
}
public function setname($v)
{
$this->name = $v;
}
public function getbiography()
{
return $this->biography;
}
public function setbiography($v)
{
$this->biography = $v;
}
}
通过reflectionclass,我们可以得到person类的以下信息:
1.常量 contants
2.属性 property names
3.方法 method names
4.静态属性 static properties
5.命名空间 namespace
6.person类是否为final或者abstract
只要把类名"person"传递给reflectionclass就可以了:
$class = new reflectionclass('person');
获取属性(properties):
$properties = $class->getproperties();
foreach($properties as $property) {
echo $property->getname()."\n";
}
// 输出:
// _allowdynamicattributes
// id
// name
// biography
默认情况下,reflectionclass会获取到所有的属性,private 和 protected的也可以。如果只想获取到private属性,就要额外传个参数:
$private_properties = $class->getproperties(reflectionproperty::is_private);
可用参数列表:
reflectionproperty::is_static
reflectionproperty::is_public
reflectionproperty::is_protected
reflectionproperty::is_private
如果要同时获取public 和private 属性,就这样写:reflectionproperty::is_public | reflectionproperty::is_protected
应该不会感觉陌生吧。
通过$property->getname()可以得到属性名,通过getdoccomment可以得到写给property的注释。
foreach($properties as $property) {
if($property->isprotected()) {
$docblock = $property->getdoccomment();
preg_match('/ type\=([a-z_]*) /', $property->getdoccomment(), $matches);
echo $matches[1]."\n";
}
}
// output:
// primary_autoincrement
// varchar
// text
有点不可思议了吧。竟然连注释都可以取到。
获取方法(methods):通过getmethods() 来获取到类的所有methods。返回的是reflectionmethod对象的数组。不再演示。
最后通过reflectionmethod来调用类里面的method。
$data = array("id" => 1, "name" => "chris", "biography" => "i am am a php developer");
foreach($data as $key => $value) {
if(!$class->hasproperty($key)) {
throw new exception($key." is not a valid property");
}
if(!$class->hasmethod("get".ucfirst($key))) {
throw new exception($key." is missing a getter");
}
if(!$class->hasmethod("set".ucfirst($key))) {
throw new exception($key." is missing a setter");
}
// make a new object to interact with
$object = new person();
// get the getter method and invoke it with the value in our data array
$setter = $class->getmethod("set".ucfirst($key));
$ok = $setter->invoke($object, $value);
// get the setter method and invoke it
$setter = $class->getmethod("get".ucfirst($key));
$objvalue = $setter->invoke($object);
// now compare
if($value == $objvalue) {
echo "getter or setter has modified the data.\n";
} else {
echo "getter and setter does not modify the data.\n";
}
}
有点意思吧。