相关疑难解决方法(0)

在PHP中是否有用于数据库访问的单例的用例?

我通过PDO访问我的MySQL数据库.我正在设置对数据库的访问权限,我的第一次尝试是使用以下内容:

我想到的第一件事是global:

$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'root', 'pwd');

function some_function() {
    global $db;
    $db->query('...');
}
Run Code Online (Sandbox Code Playgroud)

这被认为是一种不好的做法.一点点搜索后,我结束了与Singleton模式,其

"适用于需要单个类实例的情况."

根据手册中的示例,我们应该这样做:

class Database {
    private static $instance, $db;

    private function __construct(){}

    static function singleton() {
        if(!isset(self::$instance))
            self::$instance = new __CLASS__;

        return self:$instance;
    }

    function get() {
        if(!isset(self::$db))
            self::$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'user', 'pwd')

        return self::$db;
    }
}

function some_function() {
    $db = Database::singleton();
    $db->get()->query('...');
}

some_function();
Run Code Online (Sandbox Code Playgroud)

当我能做到这一点时,为什么我需要相对较大的课程呢?

class Database {
    private static $db;

    private function __construct(){}

    static function get() …
Run Code Online (Sandbox Code Playgroud)

php oop singleton design-patterns

136
推荐指数
7
解决办法
4万
查看次数

php singleton数据库连接,这个代码是不好的做法?

我正在尝试创建一个简单的使用单例类连接到mysql数据库并进行查询,代码工作正常,我没有遇到任何问题,但因为我是OOP的新手,我想知道这是否是不好的做法.

这是班级

class Database {
private $databaseName = 'dbname';
private $host = 'localhost';
private $user = 'user';
private $password = 'pass'; 
private static $instance; //store the single instance of the database

private function __construct(){
    //This will load only once regardless of how many times the class is called
    $connection = mysql_connect($this->host, $this->user, $this->password) or die (mysql_error());
    $db = mysql_select_db($this->databaseName, $connection) or die(mysql_error()); 
    echo 'DB initiated<br>';
}

//this function makes sure there's only 1 instance of the Database class
public static …
Run Code Online (Sandbox Code Playgroud)

php mysql oop singleton class

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

oop ×2

php ×2

singleton ×2

class ×1

design-patterns ×1

mysql ×1