PHP 8.1 – New setAccessible() Reflection method

PHP 8.1 – New setAccessible() Reflection method

city lights blur
For any private method ReflectionMethod or class property ReflectionProperty we can now set its accessibility and call it manually without getting any errors.

This feature includes:

  • make `ReflectionProperty` and `ReflectionMethod` behave as if `#setAccessible(true)` had been called upfront
  • make `ReflectionProperty#setAccessible()` and `ReflectionMethod#setAccessible()` no-op operations, with no side-effects nor state mutation involved

After the RFC is successfully accepted/implemented, the following code should no longer throw, improving therefore the ergonomics around reflection.

class Foo { private $bar = 'a'; }
 
(new ReflectionProperty(Foo::class, 'bar'))->getValue();

More about PHP 8.1

Read about all PHP 8.1 features and changes in here.