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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题