Tusar Nill Tusar Nill - 1 year ago 37
PHP Question

I cannot make code run that shows error is like Using $this when not in object context?

<?php class DB{

public static $conn;

public function __construct(){
try {
$this->conn = new \PDO( 'mysql:host=' . Route::get('mysql/host') . '; dbname='. Route::get('mysql/db'), Route::get('mysql/username'), Route::get('mysql/password') );
$this->conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return $this->conn;

} catch (PDOException $e) {
die('Sorry cannot connect!');

public function __destruct(){

public static function db_query($query, $bindings){
$stmt = $this->conn->prepare($query);
$res = $stmt->fetchAll();
return $res ? $res : false;


problem is how can i pass the connection to another function to avoid errors like above. please help?


You cannot use $this in static function. This is quote from PHP manual:

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

You can change db_query() to non-static and call it like $db->db_query() instead of DB::db_query()