-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;
    }
}

其余的都是非常基本的,除了当你需要查询数据库时,你必须$this->_pdo->query()在成员函数中使用

于 2012-10-22T08:07:34.333 回答