不在对象上下文中使用 $this ? [英] Using $this when not in object context?
本文介绍了不在对象上下文中使用 $this ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
错误信息:
致命错误:使用 $this 时不在 class.db.php 中的对象上下文中 - 51
Fatal error: Using $this when not in object context in class.db.php on line - 51
错误行:
return $this->PDOInstance->prepare($sql, $driver_options);
代码:
class DB {
public $error = true;
private $PDOInstance = null;
private static $instance = null;
private function __construct()
{
try {
$this->PDOInstance = new PDO('mysql:host='.HOST.';dbname='.DBNAME.';',
USER,
PASSWORD,
array(
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
));
$this->PDOInstance->query("SET NAMES 'cp1251'");
}
catch(PDOException $e) {
echo "error";
exit();
}
}
public static function getInstance()
{
if(is_null(self::$instance))
{
self::$instance = new DB();
}
return self::$instance;
}
private function __clone() {
}
private function __wakeup() {
}
public static function prepare($sql, $driver_options=array())
{
try {
return $this->PDOInstance->prepare($sql, $driver_options); /// ERROR in this line
}
catch(PDOException $e) {
$this->error($e->getMessage());
}
}
}
推荐答案
您在静态函数中使用 $this
.$this
指的是一个实例,你没有,调用静态函数,因此错误.我不明白为什么你需要在单例类中使用非静态属性,但如果你坚持拥有它们,这就是你可以做的
You're using $this
in a static function. $this
refers to an instance, which you don't have, calling a static function, hence the error. I don't see why you need non-static properties in a singleton class but in case you insist on having them this is what you can do
catch(PDOException $e) {
self::$instance->error = $e->getMessage();
}
这篇关于不在对象上下文中使用 $this ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文