PHP的Reflection反射機制

Reflection

[rɪˈflekʃn] [rɪˈflɛkʃən]

反映;(關於某課題的)思考;(聲、光、熱等的)反射;映像

 

PHP5添加了一項新的功能:Reflection。這個功能使得程序員可以增加反向工程師類,接口,函數和方法的效率(性能)並加以擴展(reverse-engineer class, interface,function,method and extension。),通過PHP代碼,就可以得到某object的所有信息,並且可以和它交互。

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命名空間 NamespacePerson類是否爲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_STATICReflectionProperty::IS_PUBLICReflectionProperty::IS_PROTECTEDReflectionProperty::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";
   }
}


有點意思啊。

http://www.php.net/manual/zh/class.reflection.php

PHP視頻教程

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章