尝试使用私有PDO对象时出错

时间:2014-08-31 20:07:19

标签: php oop pdo

所以我设置了一个允许我使用简单函数查询其中的数据库的类,但是每当我尝试使用数据库时,我都会收到以下错误: Using $this when not in object context

我的代码:

class Test {
    // Database variables
    private $DB, $DBconnectString = '';

    // Construct method (works perfectly)
    function __construct(){
        try {
            $this->DB = new PDO($this->DBconnectString, static::DATABASE_USERNAME, static::DATABASE_PASSWORD);
            $this->DB -> exec("SET CHARACTER SET utf8");
            $this->DB -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOexception $error) {
            error_log($error);
            die('Could not connect to the database');
        }
    }

    // I get an error whenever I try to query from the database.
    public static function test() {
        $query = $this->DB->prepare('SELECT * FROM `testable`');
        $query -> execute($data);
    }
}

// I call this function like this:
$Test= new Test();
$Test->test();

1 个答案:

答案 0 :(得分:0)

错误发生在public static,删除了修复代码的static关键字。