
最近在琢磨如何用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!