文字

Reflection 类

(PHP 5)

简介

反射(reflection)类。

类摘要

Reflection {
public static string export ( Reflector $reflector [, bool $return = false ] )
public static array getModifierNames ( int $modifiers )
}

Table of Contents

  • Reflection::export — Exports
  • Reflection::getModifierNames — 获取修饰符的名称

用户评论:

[#1] apmithani at yahoo dot com [2010-08-26 09:05:43]

Here is a code snippet for some of us who are just beginning with reflection. I have a simple class below with two properties and two methods. We will use reflection classes to populate the properties dynamically and then print them:

<?php

class A
{
    public 
$one '';
    public 
$two '';
    
    
//Constructor
    
public function __construct()
    {
        
//Constructor
    
}
    
    
//print variable one
    
public function echoOne()
    {
        echo 
$this->one."\n";
    }

    
//print variable two    
    
public function echoTwo()
    {
        echo 
$this->two."\n";
    }
}

//Instantiate the object
$a = new A();

//Instantiate the reflection object
$reflector = new ReflectionClass('A');

//Now get all the properties from class A in to $properties array
$properties $reflector->getProperties();

$i =1;
//Now go through the $properties array and populate each property
foreach($properties as $property)
{
    
//Populating properties
    
$a->{$property->getName()}=$i;
    
//Invoking the method to print what was populated
    
$a->{"echo".ucfirst($property->getName())}()."\n";
    
    
$i++;
}

?>

上一篇: 下一篇: