最近在琢磨如何用PHP實現站點的插件功能,需要用到反射,于是現學了一下,筆記如下:
class Person {public $name = 'Lily';public $gender = 'male';public $age = 20;public function eat(){echo 'Lily is eating!';}public function run(){echo 'Lily is running!';} } $ref = new ReflectionClass(Person::class); $methods = $ref->getMethods(); foreach ($methods as $method) {$method->invoke(new $method->class, $method->name); }
1、反射類
2、獲取類的方法
3、遍歷并執行方法
輸出結果:
Lily is eating!
Lily is running!
?