-4

This is my class, a simple pdo wrapper. It throws this error when I'm calling query function from my main page:

Using $this when not in object context

When I tried calling query from __construct it works fine.

Can anyone please help?

$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;
    }
}
Luke
  • 3,985
  • 1
  • 20
  • 35
Junjie Tan
  • 35
  • 2
  • 5

1 Answers1

0

You can't use static function query and $this together, because you don't have class object that is represented within $this. Still can use self::.

Justinas
  • 41,402
  • 5
  • 66
  • 96