略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: ReflectionMethod::setAccessible

2024-11-14

ReflectionMethod::setAccessible

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

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

说明

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

设置方法是否可以访问,例如通过设置可以访问能够执行私有方法和保护方法

参数

accessible

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

返回值

没有返回值。

参见

add a noteadd a note

User Contributed Notes 1 note

up
18
dave1010 at gmail dot com
11 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

官方地址:https://www.php.net/manual/en/reflectionmethod.setaccessible.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3