這對於存取私有方法很方便,但請記住,通常會將事物設為私有是有原因的!單元測試是其中一種(有爭議的)使用情況。
範例
<?php
class Foo {
private function myPrivateMethod() {
return 7;
}
}
$method = new ReflectionMethod('Foo', 'myPrivateMethod');
$method->setAccessible(true);
echo $method->invoke(new Foo);
// 輸出 "7"
?>
這與 PHPUnit 搭配使用效果很好:https://php.dev.org.tw/manual/en/reflectionmethod.setaccessible.php