rfc:make-reflection-setaccessible-no-op

This is an old revision of the document!


PHP RFC: #[Deprecated] Attribute

Introduction

The `ext-reflection` API is designed to inspect static details of a code-base, as well as reading and manipulating runtime state and calling internal details of objects that are otherwise inaccessible.

These methods are most notably:

  • `ReflectionMethod#invoke(): mixed`
  • `ReflectionMethod#invokeArgs(mixed ...$args): mixed`
  • `ReflectionProperty#getValue(object $object): mixed`
  • `ReflectionProperty#setValue(object $object, mixed $value): void`

While breaking encapsulation principles that allow for safe coding practices, these methods are extremely valuable to tools like:

  • mappers
  • serializers
  • debuggers
  • etc.

Infrastructural instrumentation is often required to do things that are in direct conflict with encapsulation itself.

The 4 methods listed above change behavior depending on the only mutable state within the scope of `ext-reflection` classes, which is an “accessible” flag. This “accessibility” flag is steered by:

  • `ReflectionMethod#setAccessible(bool $accessible): void`
  • `ReflectionProperty#setAccessible(bool $accessible): void`

Attempting to use any of the above listed methods without configuring accessibility first will lead to an exception being thrown. For example:

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

https://3v4l.org/ousrD :

Fatal error: Uncaught ReflectionException: Cannot access non-public property Foo::$bar in <SNIP>
rfc/make-reflection-setaccessible-no-op.1623600350.txt.gz · Last modified: 2021/06/13 16:05 by ocramius