PHP反射
阿新 • • 發佈:2017-12-18
php 反射 reflection <?php
declare(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反射