在类之外调用私有方法

本文阅读大概需要 1 分钟
1
2
3
4
5
6
7
8
9
class Test
{
private $prefix = 'Hello ';

private function hello($name)
{
echo $this->prefix, $name, PHP_EOL;
}
}

第一种方式:

1
2
3
4
$class = new \ReflectionClass(Test::class);
$method = $class->getMethod('hello');
$method->setAccessible(true);
$method->invoke(new Test(), 'Light');

第二种方式:

1
2
3
$class = new \ReflectionClass(Test::class);
$method = $class->getMethod('hello');
call_user_func($method->getClosure(new Test()), 'Light');