PHP中的单例模式 [英] Singleton pattern in php
问题描述
class SingleTon
{
private static $instance;
private function __construct()
{
}
public function getInstance() {
if($instance === null) {
$instance = new SingleTon();
}
return $instance;
}
}
上面的代码描述了本文的Singleton模式. http://www.hiteshagrawal.com/php/singleton-class-in -php-5
The above code depicts Singleton pattern from this article. http://www.hiteshagrawal.com/php/singleton-class-in-php-5
我不明白一件事.我将此类加载到项目中,但是最初如何创建Singleton对象.我可以这样叫Singelton :: getInstance()
I did not understand one thing. I load this class in my project, but how would I ever create an object of Singleton initially. Will I call like this Singelton :: getInstance()
有人可以告诉我建立数据库连接的Singleton类吗?
Can anyone show me an Singleton class where database connection is established?
推荐答案
如何为数据库类实现Singleton模式的示例如下:
An example of how you would implement a Singleton pattern for a database class can be seen below:
class Database implements Singleton {
private static $instance;
private $pdo;
private function __construct() {
$this->pdo = new PDO(
"mysql:host=localhost;dbname=database",
"user",
"password"
);
}
public static function getInstance() {
if(self::$instance === null) {
self::$instance = new Database();
}
return self::$instance->pdo;
}
}
您将通过以下方式使用该类:
You would make use of the class in the following manner:
$db = Database::getInstance();
// $db is now an instance of PDO
$db->prepare("SELECT ...");
// ...
$db = Database::getInstance();
// $db is the same instance as before
Singleton
界面如下所示,仅供参考:
And for reference, the Singleton
interface would look like:
interface Singleton {
public static function getInstance();
}
这篇关于PHP中的单例模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!