- var_dump: documentation ( source)
- is_callable: documentation ( source)
- sprintf: documentation ( source)
<?php
class Database
{
protected static $instance;
protected $pdo;
protected function __construct()
{
$this->pdo = new PDO('sqlite::memory:');
}
public static function instance()
{
if (null === self::$instance) {
self::$instance = new self;
}
return self::$instance;
}
/**
* @return PDOStatement|false
*/
public function run($sql, $args = [])
{
if (!$args) {
return $this->query($sql);
}
if ($stmt = $this->prepare($sql)) {
if ($stmt->execute($args)) {
return $stmt;
}
}
return false;
}
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
$db = Database::instance();
var_dump($db->run('SELECT ?', ['foo', 'bar'])); //false