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'));

preferences:
24.57 ms | 404 KiB | 5 Q