PHP类问题当不在对象上下文中时使用$ this

时间:2014-09-17 14:23:49

标签: php class pdo

这是我的类,一个简单的pdo包装器。当我从主页调用查询功能时,它会抛出此错误:

  

不在对象上下文中时使用$ this

当我尝试从__construct调用查询时,它运行正常。

有人可以帮忙吗?

$db = new Database();
$db->query("some sql");


class Database
{
    public $connectionString;
    public $_PDOInstance = "";

    public function __construct($errorCallbackFunction = "",$errorFormat = "")
    {
        global $vars;

        if(!$this->_PDOInstance)
        {
            if(empty($errorCallbackFunction))
            {
                $errorCallbackFunction = "print_r";
            }

            if(empty($errorFormat))
            {
                $errorFormat = "html";
            }

            if(strtolower($errorFormat) !== "html")
            {
                $errorFormat = "text";
            }

            $this->_errorMsgFormat = strtolower($errorFormat);
            $this->_errorCallbackFunction = $errorCallbackFunction;

            $dsn = "mysql:host=".$vars['dbi']['host'].";dbname=".$vars['dbi']['name'].";";
            $this->connectionString = $dsn;
            $driver_options =   array(
                                    PDO::ATTR_PERSISTENT => false,
                                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                                );
            try
            {
                $this->_PDOInstance = new PDO($dsn, $vars['dbi']['user'], $vars['dbi']['pass'], $driver_options);
                $this->_PDOInstance->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('dbStatement'));
                $this->_PDOInstance->query('SET NAMES utf8');       
            } 
            catch(PDOException $e)
            { 
                $msg = $e->getMessage();
                exit("PDO CONNECTION ERROR: ".$msg. "<br/>");
            }
        }
        return $this->_PDOInstance;
    }

    public static function query($statement)
    {           
        try
        {
            $stuff = $this->_PDOInstance->query($statement);
        }
        catch(PDOException $e)
        {
            $msg = $e->getMessage();

            if(ENV !== 'live')
            {
                print_r("Error : ".$msg."<br>"."SQL : ".$statement);
            }
            throw new PDOException($msg);
        }
        return $stuff;
    }
}

1 个答案:

答案 0 :(得分:0)

您不能同时使用static function query$this,因为您没有在$this内表示的类对象。仍然可以使用self::