A little question about singleton mode

WBOY
Release: 2023-03-01 14:06:02
Original
833 people have browsed it

Recently, I started some small projects and came into contact with the simple profit model. Based on the principle of hiding information as much as possible when defining classes, I wrote the following classes

<code>class openGate{
        private $dbname='mysql:host=localhost;dbname=project';
        private    $username='root';
        private    $password='root';
        private static $key=null;
        private function __construct(){}
        private function __clone(){}
        public static function gateKey(){
            if (self::$key==null) {
                self::$key=new openGate();
                return self::$key->gateWay();
            }
            return self::$key->gateway();
        }
        public function gateWay(){
            return new PDO($this->dbname,$this->username,$this->password);
        }
    }
    $person=openGate::gateKey();
    var_dump($person);</code>
Copy after login

Excuse me, how does this compare with the following

<code>class openGate{
        private static $key=null;
        private function __construct(){}
        private function __clone(){}
        public static function gateKey(){
            if (self::$key==null) {
                $dbname='mysql:host=localhost;dbname=project';
                $username='root';
                $password='root';
                return self::$key=new PDO($dbname,$username,$password);
            }
            return self::$key;
        }
    }
    $person=openGate::gateKey();
    var_dump($person);</code>
Copy after login

What are the pros and cons, or is it just redundant?

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template