为什么我的pdo对象返回object(pdo)[2]

798qvoo8  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(396)

嗨,我正在使用pdo为mysql开发一个基本的数据库连接类,但是当我var dump返回结果时,它告诉我有2个对象: object(PDO)[2] . 不是只有一个吗?
以下是我目前的代码:

class DBConnection
{
    // Settings (DSN)
    protected $driver, $host, $name, $charset;

    // Credentials
    protected $user, $pass;

    // PDO Connection
    protected $connection;

    public function __construct() {
        require_once( 'database.config.php' );

        // Settings (DSN)
        $this->driver   = DB_DRIVER;
        $this->host     = DB_HOST;
        $this->name     = DB_NAME;
        $this->charset  = DB_CHARSET;

        // Credentials
        $this->user     = DB_USER;
        $this->pass     = DB_PASS;

        // Initialise Connection
        var_dump($this->getConnection());
    }

    private function getConnection() {
        // Check if connection is already established
        if ( $this->connection == NULL ) {
            $dsn = "$this->driver:host=$this->host;dbname=$this->name;charset=$this->charset";
            try {
                $this->connection = new PDO($dsn,$this->user, $this->pass);
                $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch ( PDOException $error ) {
                echo 'Connection failed: ' . $error->getMessage();
            }
        }
        return $this->connection;
    }
}

$new = new DBConnection();

配置文件:

define('DB_DRIVER', 'mysql');
define('DB_HOST', 'localhost');
define('DB_NAME', 'test');
define('DB_CHARSET', 'utf8');
define('DB_USER', 'root');
define('DB_PASS', '');
monwx1rj

monwx1rj1#

private function getConnection() {
    // Check if connection is already established
    if ( $this->connection == NULL ) {
        $dsn = "$this->driver:host=$this->host;dbname=$this->name;charset=$this->charset";
        try {
            $this->connection = new PDO($dsn,$this->user, $this->pass);
            $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            // This line is to remove associate array, then you will get only one object in result set
            $this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 
        } catch ( PDOException $error ) {
            echo 'Connection failed: ' . $error->getMessage();
        }
    }
    return $this->connection;
}

相关问题