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;
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; } }
有点不可思议了吧。竟然连注释都可以取到。 获取方法(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.
"; } else { echo "Getter and Setter does not modify the data.
"; } }