简体   繁体   English

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

[英]Why does my PDO object return object(PDO)[2]

Hi i am working on a basic databse connection class for mysql using PDO, however when i var dump the return result it tells me i has 2 objects: object(PDO)[2] . 嗨,我正在使用PDO为mysql开发基本的数据库连接类,但是当我var dump返回结果时,它告诉我我有2个对象: object(PDO)[2] Should it not be only one ? 不应该只有一个吗?

Here is my code so far: 到目前为止,这是我的代码:

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();

Config file: 配置文件:

define('DB_DRIVER', 'mysql');
define('DB_HOST', 'localhost');
define('DB_NAME', 'test');
define('DB_CHARSET', 'utf8');
define('DB_USER', 'root');
define('DB_PASS', '');
    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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM