最近在開始一些小專案,接觸到單利模式,本著定義類別的時候,盡可能的隱藏資訊的原則,我對類別進行了以下的編寫
<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>
請問一下,這樣和以下相比
<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>
有哪些優缺點,或只是單純的多餘呢?