-7
<?php

//db connection class using singleton pattern
class dbConn {
    //variable to hold connection object.
    protected static $db;

    //private construct – class cannot be instatiated externally.
    private function __construct()
    {

        try { // assign PDO object to db variable
            self::$db = new PDO('mysql:host=localhost;dbname=cricket', 'root', '');
            setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) { //Output error – would normally log this to error file rather than output to user.
            echo "Connection Error: " . $e->getMessage();
        }
    }

    // get connection function. Static method – accessible without instantiation
    public static function getConnection()
    {
        //Guarantees single instance, if no connection object exists then create one.
        if (!self::$db) { //new connection object.
            new dbConn();
        }
    //return connection.
    return self::$db;
    }
}
//end class

?>

このパラメータをインデックスのように呼び出すと、このエラーを確認してください

    $sql = "select * from user";
    $q = dbConn::getConnection()->query($sql);

   $result =  $q->fetch();
    print_r($result);
}

チュートリアルリンク: http://weebtutorials.com/2012/03/pdo-connection-class-using-singleton-pattern/

4

1 に答える 1

6

コードにはいくつかの問題があります (PHP でのシングルトン パターンの有用性は別として):

シングルトンの考え方は、インスタンスがプライベートな静的変数によって参照されるということですが、コードではそうではなく、PDO オブジェクトのインスタンスを参照します。コードの真のシングルトン バージョンは次のようになります。

class TrueSingleton
{
    private static $_instance;
    private $_pdo;

    private function __construct()
    {//private constructor:
        $this->_pdo = new PDO();//<-- connect here
        //You set attributes like so:
        $this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        //not setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);<-- PHP can't know which setAttribute method to call on what object
    }
    public static function getConnection()
    {
        if (self::$_instance === null)//don't check connection, check instance
        {
            self::$_instance = new TrueSingleton();
        }
        return self::$_instance;
    }
    //to TRULY ensure there is only 1 instance, you'll have to disable object cloning
    public function __clone()
    {
        return false;
    }
    public function __wakeup()
    {
        return false;
    }
}

残りはかなり基本的なものですが、DB にクエリを実行する必要がある場合はいつでも$this->_pdo->query()、メンバー関数内で使用する必要があります

于 2012-10-22T08:07:34.333 に答える