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類別的以下資訊:
常數Contants
#屬性Property Names
方法Method Names
#靜態屬性Static Properties
命名空間 Namespace
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
$private_properties = $class->getProperties(ReflectionProperty::IS_PRIVATE);
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"; } }
以上是php Reflection反射機制實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!