3v4l.org

run code in 300+ PHP versions simultaneously
<?php declare(strict_types=1); final class Immutable { private $data; private $mutable = true; public function __construct(array $args) { if (false === $this->mutable) { throw new \BadMethodCallException('Constructor called twice.'); } $this->data = $this->sanitiseInput($args); $this->mutable = false; } public function getData(): array { return $this->data; } public function sanitiseInput(array $args): array { return array_map(function($x) { if (is_scalar($x)) return $x; else if (is_object($x)) return $this->sanitiseObject($x); else if (is_array($x)) return $this->sanitiseInput($x); else throw new \InvalidArgumentException('Resources cannot be made immutable.'); }, $args); } private static function sanitiseObject(Immutable $object): Immutable { return clone $object; } public function __clone() { $this->data = $this->sanitiseInput($this->data); } public function __unset(string $id): void {} public function __set(string $id, $val): void {} } $a = new Immutable([new stdClass, 10, 'yayaya']); $b = new Immutable([1]); var_dump($a); var_dump($b);

preferences:
76.52 ms | 402 KiB | 5 Q