4

I'm attempting to create a Trait to make "freezable value objects". (To avoid positional parameters and telescoping constructors.) This means the setters can be used to initialize the object, and then ->freeze() is called, which makes the object "immutable". The setters will still be there, but when called, they will throw an exception. This can be achieved with a $this->assertIsWritable(); call at the start of each setter. However I'd like to avoid this (as its easy to forget such a call) and do this check automatically. Is there a way to intercept calls to defined methods?

Not acceptable in the solution:

  • Approaches that break type hinting and/or static code analysis
  • Dependence on special PHP extensions

I'm using PHP 7.0.

Jeroen De Dauw
  • 10,321
  • 15
  • 56
  • 79
  • 1
    Something in runkit maybe? Possibly [`method_redefine`](http://php.net/manual/en/function.runkit-method-redefine.php). I'm not aware of any way you could do it in a trait though. – Ben Harold Jan 13 '16 at 02:03

1 Answers1

1

This is not possible without modifying the runtime (using extensions such as Runkit or uopz or performing source code transformation on your PHP code while it being loaded (using stream wrapper magic).

Sebastian Bergmann
  • 7,837
  • 1
  • 27
  • 35