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 // You could also just define a private $sealed property on the trait instead of storing this // statically, but then the object instances would have this tacked-on $sealed property, which // isn't great either. // Again, 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 git.master, git.master_jit, rfc.property-hooks
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/sK0Qm:8 Stack trace: #0 /in/sK0Qm(44): ImmutableThingy->__set('foo', 'baz') #1 {main} thrown in /in/sK0Qm on line 8
Process exited with code 255.

This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.

Active branches

Archived branches

Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page


preferences:
57.47 ms | 401 KiB | 8 Q