3v4l.org

run code in 300+ PHP versions simultaneously
<?php trait Immutable { private $_defaultValues = []; private $_userDefinedValues = []; private $_userDefinedProperties = []; private static $_doNotTakeOverProperties = [ '_defaultValues' => true, '_userDefinedValues' => true, '_userDefinedProperties' => true, ]; final public function __construct() { var_dump("in trait constructor"); // take over all user-defined non-static properties foreach ((new \ReflectionObject($this))->getProperties() as $property) { $propertyName = $property->getName(); if (isset(self::$_doNotTakeOverProperties[$propertyName]) || $property->isStatic()) { continue; } $this->_userDefinedProperties[$propertyName] = true; $this->_defaultValues[$propertyName] = $property->getValue($this); unset($this->{$property->getName()}); } } final public function __set($name, $value) { if (!isset($this->_userDefinedProperties[$name])) { throw new \LogicException('Unknown property "' . $name . '"'); } if (array_key_exists($name, $this->_userDefinedValues)) { throw new \LogicException('You can not overwrite the value for property "' . $name . '"'); } $this->_userDefinedValues[$name] = $value; } final public function __get($name) { if (!isset($this->_userDefinedProperties[$name])) { throw new \LogicException('Unknown property "' . $name . '"'); } if (array_key_exists($name, $this->_userDefinedValues)) { return $this->_userDefinedValues[$name]; } return $this->_defaultValues[$name]; } } class Foo { use Immutable; public $poo; public function __construct() { var_dump("in class constructor"); parent::__construct(); } } $foo = new Foo; $foo->poo = 1; $foo->poo = 2;

preferences:
41.02 ms | 402 KiB | 5 Q