I have
class Check
{
public function __construct()
{
$this->db = new Database();
}
public function query()
{
$login = Session::get("login");
$sth = $this->db->prepare('SELECT admin FROM accounts WHERE login=:login');
$sth->execute(array(':login' => $login));
$result = $sth->fetch(PDO::FETCH_NUM);
return $result[0];
}
public static function admin()
{
echo self::query();
}
}
I have Database class in another place with PDO connection.
class Database extends PDO
{
public function __construct()
{
parent::__construct('mysql:host=localhost;dbname=name','root','pass');
$this->query('SET NAMES utf8');
}
}
So after Check::admin() code I get error:
Undefined property: View::$db
Why?
You are using a
staticmethod, that wants to use ainstancevariable.Your admin method calls the query method, and the query method is using the
dbinstance variable. As your class is not instantiated, thedbvariable does not exists.My suggestion would be to make the admin method non static and use your code like this:
or, if you are on php 5.4 and want to stick with a oneliner:
update
note: Do not create the
dbclass in the constructor, but inject it: