douhutongvm382381 2012-03-22 13:59
浏览 33
已采纳

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

i have these in 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();
    }


}

in try to call him on index.php

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

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

echo $ret['id'];
?>

but response :

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

is there anyone could help ? thank in advance

  • 写回答

4条回答 默认 最新

  • dongtan1845 2012-03-22 14:09
    关注

    In your static method, you are using the instance accessor $this-> which is not valid syntax. Typically, you would need to use self::, but it isn't as simple as that. Take a look at this question, it should explain the difference between using self (when in static methods) and $this (when in non-static methods).

    From a glance at the code though, the Database class requires you to instantiate the object in order to create the DB instance utilised later on. For this reason, it would make more sense to make your query methods fetch_a_row and exec non-static, and change your code to instantiate the object and use that instance.

    However, this is all stuff that you must figure out as the Database class needs a bit of refactoring in order to work. The first thing to ask yourself would be "why are you utilising static methods?" - if you don't need them, it may be simpler to use non-statics (as mentioned above). From there, I guess it's up to you the direction you take.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私
  • ¥15 扫描枪扫条形码出现问题
  • ¥35 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?