Adding ping() function to PDO

Recently helped my colleague to add the missing mysqli_ping() function to PDO object in PHP. If anyone missed it, here it is:

class NPDO {
    private $pdo;
    private $params;

    public function __construct() {
        $this->params = func_get_args();

    public function __call($name, array $args) {
        return call_user_func_array(array($this->pdo, $name), $args);

    // The ping() will try to reconnect once if connection lost.
    public function ping() {
        try {
            $this->pdo->query('SELECT 1');
        } catch (PDOException $e) {
            $this->init();            // Don't catch exception here, so that re-connect fail will throw exception

        return true;

    private function init() {
        $class = new ReflectionClass('PDO');
        $this->pdo = $class->newInstanceArgs($this->params);

6 thoughts on “Adding ping() function to PDO

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s