PHP通過反射實現對象的成員方法調用
阿新 • • 發佈:2017-12-23
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);
}
實現ReflectionClass對象
實現ReflectionMethod對象
實現ReflectionParameter對象
通過反射實現對象的依賴註入
PHP通過反射實現對象的成員方法調用