【发布时间】:2023-03-22 06:14:01
【问题描述】:
错误信息:
致命错误:使用 $this 时 不在第 51 行的 class.db.php 中的对象上下文中
错误行:
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());
}
}
}
【问题讨论】:
-
你的
prepare方法被声明为static,但是如果你静态调用一个方法,你就不能使用$this,因为没有对象。