<?phpdeclare(strict_types=1);//开启强类型模式class Person{ public $name; protected $hobbies = []; private $age; /** * 构造器 * Person constructor. * @param string $name * @param array $hobbies * @param int $age */ public function __construct(string $name, array $hobbies, int $age) { $this->name = $name; $this->hobbies = $hobbies; $this->age = $age; } /** * 判断是否符合人类的喜好 * @param string $hobby * @return bool */ public function checkHobby(string $hobby) { if (in_array($hobby, $this->hobbies)) { echo $this->name . ' very like ' . $hobby . PHP_EOL; } else { echo $this->name . ' not like ' . $hobby . PHP_EOL; } }}//1.获取指定类的反射类对象(初始化新的 ReflectionClass 对象。 )//public ReflectionClass::__construct ( mixed $argument )$reflectionClass = new ReflectionClass('Person');//2.获取反射类对象的实例(即反射实例)//public object ReflectionClass::newInstance ( mixed $args [, mixed $... ] )$reflectionInstance = $reflectionClass->newInstance('zhangsan', ['吃饭', '睡觉', '打豆豆'], 18);// 创建类的新的实例。给出的参数将会传递到类的构造函数。/** * Person Object * ( * [name] => zhangsan * [hobbies:protected] => Array * ( * [0] => 吃饭 * [1] => 睡觉 * [2] => 打豆豆 * ) * [age:Person:private] => 18 * ) * *///public object ReflectionClass::newInstanceArgs ([ array $args ] )//$reflectionInstance1 = $reflectionClass->newInstanceArgs(['zhangsan', ['吃饭', '睡觉', '打豆豆'], 18]);// 创建类的新的实例。给出的参数将会传递到类的构造函数。//echo $reflectionInstance == $reflectionInstance1;//3.获取成员方法的反射方法类 ReflectionMethod( 获取一个类方法的 ReflectionMethod。)//public ReflectionMethod ReflectionClass::getMethod ( string $name )$reflectionMethod = $reflectionClass->getMethod('checkHobby');//4.执行一个反射的方法。//public mixed ReflectionMethod::invoke ( object $object [, mixed $parameter [, mixed $... ]] )//参数解析://$object为反射类的实例对象,//$parameter为要反射的类的成员方法参数echo $reflectionMethod->invoke($reflectionInstance, 'coding php');echo $reflectionMethod->invoke($reflectionInstance, '吃饭');echo $reflectionMethod->invokeArgs($reflectionInstance, ['coding Java']);echo $reflectionMethod->invokeArgs($reflectionInstance, ['dream']);//(new Person('lisi', ['run', 'footbool', 'climb mountains'], 25))->checkHobby('Python');
PHP反射
原文地址:http://blog.51cto.com/phpme/2051659