執行個體介紹PHP的Reflection反射機制_php執行個體

來源:互聯網
上載者:User

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";
   }
}

有點意思吧。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.