PHP 具有完整的反射 API,增加了内省类、接口、函数、方法和扩展的能力。 此外,反射 API 提供了方法来取出函数、类和方法中的文档注释。
A.php
<?php/*** 类的注释*/
class A
{public $one = '';public $two = '';//Constructorpublic function __construct(){//Constructor}//print variable onepublic function echoOne($a,$b){return "echoOne---- {$a}|{$b}";}/*** print variable two*/public function echoTwo(){return "echoTwo\n";}
}
反射获取相关信息实例
/*** 反射* @return void*/public function reflectDemo(){//Instantiate the object$a = new \A();var_dump($a);// Instantiate the reflection object$reflector = new \ReflectionClass($a);//Now get all the properties from class A in to $properties array$properties = $reflector->getProperties();var_dump($properties);$i =1;//Now go through the $properties array and populate each propertyforeach($properties as $property){//Populating properties$a->{$property->getName()}=$i;//Invoking the method to print what was populated//$a->{"echo".ucfirst($property->getName())}()."\n";$i++;}// 相当于实例化这个类 等同于上面的 $a$instance = $reflector->newInstance();
// var_dump($instance);// 方法一//invoke methodecho $instance->echoTwo();// 方法二// get method$method = $reflector->getMethod('echoOne');echo $method->invokeArgs($instance,["abd","eff"]);// 方法三 没有参数的方法$method = $reflector->getMethod('echoTwo');echo $method->invoke($instance);// 获取所有 method$methods = $reflector->getMethods();var_dump($methods);// 获取类注释 方法注释var_dump($reflector->getDocComment());var_dump($method->getDocComment());//判断某个方法是不是公共的$method = new \ReflectionMethod($a,'echoOne');if ($method->isPublic()) {echo "method is public";}// 获取方法的参数和参数个数var_dump($method->getParameters());var_dump($method->getNumberOfParameters());}