Home >Backend Development >PHP Tutorial >Singleton Theory - PHP

Singleton Theory - PHP

DDD
DDDOriginal
2024-12-06 01:55:19446browse

Singleton Theory - PHP

Singleton design pattern ensures that the application creates only 1 object at run time. 
If it is necessary to use the same object many times in the application, we can prevent it from creating instances over and over again. We can achieve this by using static with singleton design pattern.

If the object has been created before, it continues its life through that object, if not, it continues its life by creating a new object.

In memory works via RAM.

It is recommended to create a private constructor.

class DbController
{
    private static $instance;
    public static $db;

    private function __construct()
    {
        $this->db = new PDO("mysql:host=localhost;dbname=***;", "root", "");
    }

    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            self::$instance = new DbController;
        }
        return self::$instance;
    }

    public function dbConnection()
    {
        if (!isset(self::$db)) {
            self::$db = new PDO("mysql:host=localhost;dbname=***;", "root", "");
        }
        return self::$db;
    }
}
$cont1 = DbController::getInstance();
$cont2 = DbController::getInstance();
var_dump($cont1);
var_dump($cont2);
if ($cont1 === $cont2) echo 'Same';

The above is the detailed content of Singleton Theory - PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn