略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: Reflection

2024-12-23

Reflection 类

(PHP 5, PHP 7, PHP 8)

简介

反射(reflection)类。

类摘要

class Reflection {
/* 方法 */
public static export(Reflector $reflector, bool $return = false): string
public static getModifierNames(int $modifiers): array
}

目录

add a noteadd a note

User Contributed Notes 1 note

up
36
apmithani at yahoo dot com
11 years ago
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++;
}

?>

官方地址:https://www.php.net/manual/en/class.reflection.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3