问题
I get a fatal error saying that I can't use $this
variable when not in object context: -
Fatal error: Using $this when not in object context in C:\xampp\htdocs\ooplr\classes\DB.php on line 29
Essentially, I am trying to design a sophisticated user login system. Here is the code for the DB.php file:
<?php
class DB{
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_results,
$_count =0;
private function __construct(){
try {
$this->_pdo = new PDO('mysql:host='.Config::get('mysql/host').';dbname='.Config::get('mysql/db'),Config::get('mysql/username'),Config::get('mysql/password'));
} catch(PDOException $e) {
die($e->getMessage());
}
}
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance = new DB();
}
return self::$_instance;
}
public static function query($sql, $params=array()){
$this->_error = false; <--- Error code comes from this line!
if($this->_query = $this ->_pdo-> prepare($sql)){
$x=1;
if(count($params)){
foreach($params as $param){
$this -> _query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count =$this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
private function action($action, $table, $where = array()){
if(count($where)===3){
$operators = array('=','>','<','>=','<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
}
if(in_array($operator, $operators)){
$sql ="{$action} FROM {$table} WHERE {$field} {$operator} ?";
if($this->query($sql, array($value))->error()){
return $this;
}
}
return false;
}
public function get($table,$where){
return $this->action('SELECT*',$table, $where);
}
public function delete($table, $where){
return $this->action('DELETE',$table, $where);
}
public function error(){
return $this->_error;
}
}
How would I get to fix that line: $this->_error = false; and how do I put it in "object context"?
回答1:
You've declared your query
method as static. $this
requires an instance to refer to, so you can't use it in a static method.
You need to properly instantiate your class, and use non-static methods to use $this
.
Note that your __construct()
method should be declared public.
回答2:
if you want to use variables in static methods they must declare static too, so if you want to use $_error declare it:
static public $_error
and use it in static method like this:
self::$_error
来源:https://stackoverflow.com/questions/20280439/fatal-error-for-this-variable