Singleton类出了点问题,不知道怎么办 [英] Something wrong with Singleton class, no idea what
问题描述
我以前从来没有做过Singleton类,现在我发现对于这种数据库连接来说,建立一个是一个好主意,但是我不知道为什么它不起作用.如果有人愿意帮助我,我将不胜感激,因为我想学习OOP的工作原理...
I have never done any Singleton class before and now I figured that for this DB connection it will be a good idea to make one, but I have no clue why it is not working. I really would appreciate if someone would help me out with this one since I want to learn how OOP works...
无论如何,我只是通过将PHP更新到最新版本来修复它,现在$DBH = new static();
可以正常工作,谢谢大家.
Anyway, I fixed it with just updating my PHP to latest version, now $DBH = new static();
works fine, thanks people.
我尝试使用$DBH = new self();
的$DBH = new static();
istead,但随后出现此错误:
I tried to use $DBH = new static();
isntead of $DBH = new self();
but then I have this error:
解析错误:语法错误,意外 T_STATIC,预期为T_STRING或 T_VARIABLE或mSingleton.php中的"$" 第14行
Parse error: syntax error, unexpected T_STATIC, expecting T_STRING or T_VARIABLE or '$' in mSingleton.php on line 14
错误:
致命错误:无法实例化 中的抽象类Singleton 第14行的mSingleton.php
Fatal error: Cannot instantiate abstract class Singleton in mSingleton.php on line 14
文件: (mSingleton.php)
Files: (mSingleton.php)
abstract class Singleton
{
protected $DBH;
public static function getInstance()
{
if ($DBH == null)
{
$DBH = new self();
}
return $DBH;
}
}
(mDBAccess.php)
(mDBAccess.php)
<?php
//mDBAccess.php
//Removed values ofc
$db_host = "";
$db_name = "";
$db_user = "";
$db_pass = "";
include "mSingleton.php";
class DBAccess extends Singleton
{
protected $DBH;
function __construct()
{
try
{
$this->DBH = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
$this->DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
catch (PDOException $e)
{
echo $e->getMessage();
}
}
public static function getDBH()
{
return self::getInstance()->DBH;
}
}
(mLog.php)
<?php
//mLog.php
include "mDBAccess.php";
class Log
{
public static function Add($action)
{
try
{
$DBH = DBAccess::getDBH();
//Getting user IP
$ip = $_SERVER['REMOTE_ADDR'];
//Getting time
$time = date('Y-m-d');
//Preparing our SQL Query
$values = array($ip, $action, $time);
$STH = $DBH->prepare("INSERT INTO log (ip, action, time)
VALUES (?, ?, ?)");
//Excecuting SQL Query
$STH->execute($values);
}
catch (PDOException $e)
{
echo $e->getMessage();
}
}
}
//testing..
Log::Add("ddd");
推荐答案
您需要编写
$DBH = new static();
请参阅:后期静态绑定
这篇关于Singleton类出了点问题,不知道怎么办的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!