O
O
Optimus2017-01-23 13:28:05
PHP
Optimus, 2017-01-23 13:28:05

Singleton question?

I have already read about him more than once, incl. See all answers in a recent thread What is a singleton for?
Take a simple implementation without a wrapper:

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
    $pdo = new PDO($dsn, $user, $pass, $opt);
} catch...

// Далее в приложении используем
$db=$pdo->prepare(" SELECT ");

In each application instance, at the very beginning of the application, a PDO instance is created. In addition to it, there is no way to access the database, there is only one variable $pdo
Or the meaning of the singleton is that there are such systems where the left hand does not know what the right hand is doing and some programmer in another part of the system does it again $pdo2 = new PDO() and now we have $pdo and $pdo2?
Here is the implementation from phprigthway
class Singleton
{
    protected static $instance;
    
    public static function getInstance()
    {
        if (null === static::$instance) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    protected function __construct(){}
    private function __clone(){}
    private function __wakeup(){}
}

class SingletonChild extends Singleton{}

$obj = Singleton::getInstance();
\var_dump($obj === Singleton::getInstance());             // bool(true)

$anotherObj = SingletonChild::getInstance();
\var_dump($anotherObj === Singleton::getInstance());      // bool(false)

\var_dump($anotherObj === SingletonChild::getInstance()); // bool(true)

Do I understand correctly that its only difference is that there is foolproofing that does not allow creating $pdo2 as in the first example?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
kpa6uu, 2017-01-23
Pyan @marrk2

Yes that's right. In the right singletons, possible ways to create / clone them are cut :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question