致命错误:当不在数据库实例的对象上下文中时使用$ this

时间:2012-03-22 13:59:58

标签: php class sqlite

我在Database.php中有这些

class Database
{
    private $dbname = 'auth';
    private $db_instance;   

    public function __construct($q)
    {
        if(!$this->db_instance)
        $this->db_instance = new SQLite3($q);
    }

    private function init()
    {
        if(!$this->db_instance)
        {
            $this->db_instance = new SQLite3($dbname);
        }
    }

    private function close()
    {
        if($this->db_instance)
        $this->db_instance->close();
    }

    static public function fetch_a_row($q)
    {
        $this->init();
        $res = $this->db_instance->query(SQLite3::escapeString($q));
        $ret = $res->fetchArray(SQLITE3_ASSOC); 
        $this->close();

        return $ret;
    }

    static public function exec($q)
    {
        $this->init();
        $this->db_instance->exec(SQLite3::escapeString($q));
        $this->close();
    }


}

尝试在index.php上打电话给他

<?php
require_once('Database.php');

$ret = Database::fetch_a_row('SELECT * FROM user WHERE uname = "test"');

echo $ret['id'];
?>

但回应:

Fatal error: Using $this when not in object context in /www/cgi-bin/auth/Database.php on line 29

有人可以帮忙吗? 提前谢谢

4 个答案:

答案 0 :(得分:4)

在静态方法中,您使用的是无效语法的实例访问者$this->。通常,您需要使用self::,但并不是那么简单。看看this question,它应该解释使用self(在静态方法时)和$this(在非静态方法中)之间的区别。

通过一瞥代码,Database类要求您实例化对象,以便创建稍后使用的数据库实例。因此,使查询方法fetch_a_rowexec非静态更有意义,并更改代码以实例化对象并使用该实例。

然而,这是你必须弄清楚的所有东西,因为Database类需要一些重构才能工作。首先要问自己的是“为什么要使用静态方法?” - 如果你不需要它们,使用非静力学可能更简单(如上所述)。从那里开始,我想这取决于你的方向。

答案 1 :(得分:0)

您在静态函数中使用$this,因为没有上下文(因为静态引用类,而$this查找当前对象)。请改为在您的班级“self”中使用fetch_a_row

答案 2 :(得分:0)

您不能在静态上下文中使用this。从函数中删除静态并调用它:

$db = new Database();
$ret = $db->fetch_a_row('SELECT * FROM user WHERE uname = "test"');

答案 3 :(得分:0)

您必须创建数据库类的实例。

$db = new Datatbase('test');

现在你有了一个可以使用的对象

$results= $db->fetch_a_row(query);