doumen1883 2012-12-02 15:25
浏览 65
已采纳

使用类中的$ this从空值创建默认对象

I'm using a slight variation on the PHP PDO Wrapper Class found here: http://www.imavex.com/php-pdo-wrapper-class/

This is the new constructor I'm using:

public function __construct($dsn, $user='', $passwd='') {
    $options = array(
        PDO::ATTR_PERSISTENT => true, 
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    );

    try {
        parent::__construct($dsn, $user, $passwd, $options);
    } catch (PDOException $e) {
        $this->error = $e->getMessage();
    }
}

error is a private variable of this class, defined at the begin of the class, above the constructor.strong text

And when I use it like this

$database = new Database(
        'mysql:host=' . $config['mysql_host'] . ';port=' . $config['mysql_port'] . ';dbname=' . $config['mysql_database'],
        $config['mysql_username'],
        $config['mysql_password']
);

It shows me this error: Creating default object from empty value, pointing to the database class file, at the line $this->error = $e->getMessage();.

The reason an exception is thrown is because I haven't set the mysql username and password yet, so don't worry about that. I'm trying to figure out why it gives this error and how to fix it.

  • 写回答

1条回答 默认 最新

  • dpzbh1779 2012-12-18 07:23
    关注

    It seems that since the db class extends PDO, when the PDO constructor throws an exception $this becomes NULL.

    class db extends PDO {
        public function __construct($dsn, $user="", $passwd="") {
            $options = array(
                PDO::ATTR_PERSISTENT => true,
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            );
    
            try {
                parent::__construct($dsn, $user, $passwd, $options);
            } catch (PDOException $e) {
                echo "Got PDOException
    ";
                var_dump($this);
            }
        }
    }
    
    
    new db('mysql:host=localhost;port=3306;dbname=something', 'invaliduser', 'invalidpass');
    

    If you run that code you will get this output:

    Got PDOException
    NULL
    

    To solve that you could remove the offending line and check if the db object is null or remove the try-catch and do the exception handling when you instantiate a new db. Alternatively, you could rewrite the class to store the PDO object in a variable instead of extending PDO.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?