gpt4 book ai didi

php - php中的单例模式

转载 作者:可可西里 更新时间:2023-10-31 23:59:16 28 4
gpt4 key购买 nike

class SingleTon
{
private static $instance;

private function __construct()
{
}

public function getInstance() {
if($instance === null) {
$instance = new SingleTon();
}
return $instance;
}
}

以上代码描述了本文中的单例模式。 http://www.hiteshagrawal.com/php/singleton-class-in-php-5

有一件事我没看懂。我在我的项目中加载了这个类,但是我最初如何创建一个 Singleton 对象。我会这样调用吗 Singelton::getInstance()

谁能告诉我建立数据库连接的单例类?

最佳答案

下面是一个如何为数据库类实现单例模式的示例:

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;
}
}

您将按以下方式使用该类:

$db = Database::getInstance();
// $db is now an instance of PDO
$db->prepare("SELECT ...");

// ...

$db = Database::getInstance();
// $db is the same instance as before

作为引用,Singleton 界面如下所示:

interface Singleton {
public static function getInstance();
}

关于php - php中的单例模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7968154/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com