3v4l.org

run code in 300+ PHP versions simultaneously
<?php declare(strict_types=1); final class Immutable { private $data; private $mutable = true; private 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);
Output for 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.7
Fatal error: Uncaught Error: Call to private Immutable::__construct() from global scope in /in/afjT6:37 Stack trace: #0 {main} thrown in /in/afjT6 on line 37
Process exited with code 255.
Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33
Fatal error: Uncaught Error: Call to private Immutable::__construct() from invalid context in /in/afjT6:37 Stack trace: #0 {main} thrown in /in/afjT6 on line 37
Process exited with code 255.

preferences:
143.72 ms | 403 KiB | 202 Q