3v4l.org

run code in 300+ PHP versions simultaneously
<?php trait Immutable { private static $sealed = array(); public function __set($name, $value) { //if (isset(self::$sealed[spl_object_hash($this)])) { throw new Exception("can't touch this, nah nah nuh nahhh"); //} $this->$name = $value; } public function __get($name) { return $this->$name; } protected function finalize() { self::$sealed[spl_object_hash($this)] = true; // You could probably implement a __destruct to clean up and avoid leaking memory here, // but who gaf anyway this is just an example } } class ImmutableThingy { use Immutable; protected $foo; public function __construct($foo) { $this->foo = $foo; //$this->finalize(); } } $thing = new ImmutableThingy("bar"); var_dump($thing, $thing->foo); $thing->foo = 'baz'; var_dump($thing, $thing->foo);
Output for 7.0.0 - 7.0.33, 7.1.0 - 7.1.25, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
object(ImmutableThingy)#1 (1) { ["foo":protected]=> string(3) "bar" } string(3) "bar" Fatal error: Uncaught Exception: can't touch this, nah nah nuh nahhh in /in/8UkOZ:8 Stack trace: #0 /in/8UkOZ(40): ImmutableThingy->__set('foo', 'baz') #1 {main} thrown in /in/8UkOZ on line 8
Process exited with code 255.
Output for 5.5.0 - 5.5.38, 5.6.0 - 5.6.38
object(ImmutableThingy)#1 (1) { ["foo":protected]=> string(3) "bar" } string(3) "bar" Fatal error: Uncaught exception 'Exception' with message 'can't touch this, nah nah nuh nahhh' in /in/8UkOZ:8 Stack trace: #0 /in/8UkOZ(40): ImmutableThingy->__set('foo', 'baz') #1 {main} thrown in /in/8UkOZ on line 8
Process exited with code 255.

preferences:
259.23 ms | 402 KiB | 294 Q