3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Closable { public readonly string $key; private bool $closed = false; public function __construct( ?string $key = null, ) { $this->key = uniqid($key ?: 'closable_'); $this->e('__construct'); } private function e(string $out): void { echo $this->key, ': ', $out, "\n"; } public function close(): void { $this->e('close'); $this->e($this->closed ? 'already closed' : 'closing'); $this->closed = true; } public function __destruct() { $this->e('__destruct'); $this->close(); } public static function make(): Closable { return new self(); } } function a(): void { echo "a() start\n"; $a = Closable::make('$a'); echo "a() end\n"; } function b(): void { echo "b() start\n"; $b = Closable::make('$b'); try { if (rand(0,1)) { throw new Exception('b()'); } echo "b() return\n"; unset($b); return; } catch (Exception) { echo "b() catch\n"; } finally { echo "b() finally\n"; isset($b) ? $b->close() : null; } } Closable::make('first'); $foo = Closable::make('$foo'); Closable::make('third'); for ($i = 0; $i <= 10; $i++) { a(); b(); }

preferences:
33.41 ms | 405 KiB | 5 Q