在php中的单身人士模式

the*_*ava 3 php singleton

class SingleTon
{
    private static $instance;

    private function __construct()
    {
    }

    public function getInstance() {
        if($instance === null) {
            $instance = new SingleTon();
        }
        return $instance;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我不明白一件事.我在我的项目中加载了这个类,但是我最初如何创建一个Singleton对象.我会这样打电话吗?Singelton :: getInstance()

任何人都可以向我展示一个建立数据库连接的Singleton类吗?

Tim*_*per 12

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式使用该类:

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

// ...

$db = Database::getInstance();
// $db is the same instance as before
Run Code Online (Sandbox Code Playgroud)

作为参考,Singleton界面看起来像:

interface Singleton {
    public static function getInstance();
}
Run Code Online (Sandbox Code Playgroud)