CakeFest 2024: The Official CakePHP Conference

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 を指定すると、アクセスできるようになります。

戻り値

値を返しません。

例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

参考

add a note

User Contributed Notes 1 note

up
21
dave1010 at gmail dot com
12 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