3v4l.org

run code in 300+ PHP versions simultaneously
<?php final class DbConnection { private $dsn; private $initializer; public function __construct(string $dsn) { $this->dsn = $dsn; // socket stuff happens here, much like with PDO } public function query(string $queryString) : array { ($this->initializer)(); // irrelevant from here on return ['query' => $queryString, 'dsn' => $this->dsn]; } public static function lazyInstance(string $dsn) : self { $instance = (new ReflectionClass(self::class))->newInstanceWithoutConstructor(); $instance->initializer = function () use ($dsn, $instance) { $instance->__construct($dsn); $instance->initializer = function () { }; }; return $instance; } } $instance = DbConnection::lazyInstance('mysql://something'); var_dump($instance); var_dump($instance->query('SELECT * FROM foo')); var_dump($instance->query('SELECT * FROM bar'));
Output for 8.4.1
object(DbConnection)#2 (2) { ["dsn":"DbConnection":private]=> NULL ["initializer":"DbConnection":private]=> object(Closure)#1 (4) { ["name"]=> string(41) "{closure:DbConnection::lazyInstance():24}" ["file"]=> string(9) "/in/Y0eoL" ["line"]=> int(24) ["static"]=> array(2) { ["dsn"]=> string(17) "mysql://something" ["instance"]=> *RECURSION* } } } array(2) { ["query"]=> string(17) "SELECT * FROM foo" ["dsn"]=> string(17) "mysql://something" } array(2) { ["query"]=> string(17) "SELECT * FROM bar" ["dsn"]=> string(17) "mysql://something" }
Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.25, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.31, 8.2.0 - 8.2.26, 8.3.0 - 8.3.14
object(DbConnection)#2 (2) { ["dsn":"DbConnection":private]=> NULL ["initializer":"DbConnection":private]=> object(Closure)#1 (1) { ["static"]=> array(2) { ["dsn"]=> string(17) "mysql://something" ["instance"]=> *RECURSION* } } } array(2) { ["query"]=> string(17) "SELECT * FROM foo" ["dsn"]=> string(17) "mysql://something" } array(2) { ["query"]=> string(17) "SELECT * FROM bar" ["dsn"]=> string(17) "mysql://something" }
Output for 5.6.0 - 5.6.29
Parse error: syntax error, unexpected ':', expecting ';' or '{' in /in/Y0eoL on line 14
Process exited with code 255.

preferences:
81.85 ms | 409 KiB | 5 Q