3v4l.org

run code in 300+ PHP versions simultaneously
<?php /** @template T */ class InvariantCollection { /** @var list<T> */ public $values; /** @param list<T> $values */ public function __construct($values) { $this->values = $values; } } class Foo {} class Bar extends Foo {} class FooBar { /** @var InvariantCollection<Bar> */ private $bars; public function __construct() { $this->bars = new InvariantCollection([new Bar()]); } /** @return InvariantCollection<Foo> */ public function getFoos(): InvariantCollection { $bars = $this->bars; return $bars; } public function check(): void { foreach ($this->bars->values as $bar) { if (!$bar instanceof Bar) { throw new \Exception("Illegally modified!"); } } } } $foobar = new FooBar(); $foos = $foobar->getFoos(); $foos->values[] = new Foo(); $foobar->check();
Output for 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.30, 8.2.0 - 8.2.25, 8.3.0 - 8.3.13
Fatal error: Uncaught Exception: Illegally modified! in /in/Z9keJ:40 Stack trace: #0 /in/Z9keJ(49): FooBar->check() #1 {main} thrown in /in/Z9keJ on line 40
Process exited with code 255.

preferences:
81.87 ms | 406 KiB | 5 Q