3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Database { protected static $instance; protected $pdo; protected function __construct() { static $opt = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, ]; $this->pdo = new PDO('sqlite::memory:', null, null, $opt); } public static function instance() { if (null === self::$instance) { self::$instance = new self; } return self::$instance; } public function run($sql, $args = []) { if (!$args) { return $this->query($sql); } $stmt = $this->prepare($sql); $stmt->execute($args); return $stmt; } public function __call($method, $args) { if (is_callable([$this->pdo, $method])) { //php 5.6+ variadic optimization (aka splat operator) return $this->pdo->$method(...$args); //PHP <= 5.5 //return call_user_func_array(array($this->pdo, $method), $args); } throw new \BadMethodCallException(sprintf('Unknown method PDO::%s called!', $method)); } } //RunTime code if (PHP_VERSION_ID >= 70100) { try { $db = Database::instance(); var_dump($db->run('SELECT ?', ['foo', 'bar'])->fetch()); } catch(\PDOException $e) { if ('execute' === $e->getTrace()[0]['function']) { echo 'PDO::execute() failed'; } //Handle the exception } } else { try { $db = Database::instance(); var_dump($db->run('SELECT ?', ['foo', 'bar'])->fetch()); } catch(\PDOException $e) { if ('execute' === $e->getTrace()[0]['function']) { echo 'PDO::execute() failed'; } //Handle the exception } }

preferences:
29.3 ms | 402 KiB | 5 Q