PHP 8.4.1 Released!

ReflectionMethod::setAccessible

(PHP 5 >= 5.3.2, PHP 7, PHP 8)

ReflectionMethod::setAccessible设置方法是否可访问

说明

public ReflectionMethod::setAccessible(bool $accessible): void

通过 ReflectionMethod::invoke() 方法启用对 protected 或 private 方法的调用。

注意: 自 PHP 8.1.0 起,调用此方法无效;默认情况下,所有方法都可调用。

参数

accessible

可以访问设置 true,否则设置 false

返回值

没有返回值。

示例

示例 #1 简单类定义

<?php
class MyClass
{
private function
foo()
{
return
'bar';
}
}

$method = new ReflectionMethod("MyClass", "foo");
$method->setAccessible(true);

$obj = new MyClass();
echo
$method->invoke($obj);
echo
$obj->foo();
?>

以上示例的输出类似于:

bar
Fatal error: Uncaught Error: Call to private method MyClass::foo() from global scope in /in/qdaZS:16

参见

添加备注

用户贡献的备注 1 note

up
21
dave1010 at gmail dot com
13 years ago
This is handy for accessing private methods but remember that things are normally private for a reason! Unit Testing is one (debatable) use case for this.

Example:
<?php
class Foo {
private function
myPrivateMethod() {
return
7;
}
}

$method = new ReflectionMethod('Foo', 'myPrivateMethod');
$method->setAccessible(true);

echo
$method->invoke(new Foo);
// echos "7"
?>

This works nicely with PHPUnit: http://php.net/manual/en/reflectionmethod.setaccessible.php
To Top