1. 程式人生 > >PHP通過反射實現對象的成員方法調用

PHP通過反射實現對象的成員方法調用

php reflection

class Food { public $name = 'apple'; } class Person { const SEX = 'boy'; public $name; private $age; protected $hobbies = []; public function eat(Food $foodObj, string $waterName):string { return "eatting {$foodObj->name},drinking {$waterName}"; } public function hello() { return 'Hello world'; } } $instance = (new ReflectionClass('Person'))->newInstance(); $reflectionMethod = new ReflectionMethod('Person', 'eat'); //校驗成員方法是否是public,可訪問的 if (!$reflectionMethod->isPublic()) { echo '不能訪問Person類的eat方法' . PHP_EOL; return; } //ReflectionParametr對象組成的數組 $parameters = $reflectionMethod->getParameters(); if (empty($parameters)) { echo $reflectionMethod->invoke($instance); } else { $args = []; foreach ($parameters as $parameterObj) { if ($reflectionclass = $parameterObj->getClass()) { $className = $reflectionclass->getName(); $args[] = (new ReflectionClass($className))->newInstance(); } else { $args[] = 'hello'; } } echo $reflectionMethod->invoke($instance, ...$args); }


  1. 實現ReflectionClass對象

  2. 實現ReflectionMethod對象

  3. 實現ReflectionParameter對象

  4. 通過反射實現對象的依賴註入


PHP通過反射實現對象的成員方法調用