3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Closable { public readonly string $key; private bool $closed = false; public function __construct() { $this->key = uniqid('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 __destroy(): void { $this->e('__destroy'); $this->close(); } public static function make(): Closable { return new self(); } } function a(): void { echo "a() start\n"; $a = Closable::make(); echo "a() end\n"; } function b(): void { echo "b() start\n"; $b = Closable::make(); 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"; $b?->close(); } } Closable::make(); $foo = Closable::make(); Closable::make(); for ($i = 0; $i <= 10; $i++) { a(); b(); }

preferences:
31.54 ms | 405 KiB | 5 Q