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