Re: green bean question on singleton php5
| From: | Jochem Maas | Date: | Wed, 16 Jan 2008 20:59:21 +0000 |
| Subject: | Re: green bean question on singleton php5 | ||
| References: | 1 2 3 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-267440@lists.php.net to get a copy of this message | ||
julian schreef:
you are forcing the no instantiation via abstract, instead of hiding via private method constructor.you want to garantee a single instance of the mysqli object - who cares exactly how this is done. besides which the whole exercise is bogus. you want a DB connection abstraction that allows to create connections to multiple DBs and given a given set of connection parameters to always return the same connection object ... which is not exactly the same as a singleton (at all) given that dbaccess doesn't extend mysqli instantiation of dbaccess is completely pointless no?
You change the constructor for an init function. still the $dummy = new dbaccess ()..... looks like a simpler solution....no idea what you mean, personally I can't see anything complicated in any of these examples - I couldn't find a post showing something with $dummy.
Thanks for your comments Jochem Maas wrote:julian schreef:Hi, I am implementing thistry comparing this rewrite with your version: abstract class dbaccess { static $db = null; private static function init() {if (dbaccess::$db)) return;dbaccess::$db = new mysqli("localhost",USER,PASSWD,DB); if(mysqli_connect_errno()) throw new Exception('cannot connect to DB');} public static function getDB() {self::init(); return dbaccess::$db;} } try {$db = dbaccess::getDB(); $db->query("SELECT} catch (Exception) {fooFROMbarWHEREqux=1");die($e->getMessage());}class dbaccess{ static $db=null; static $othervar=33;dbaccess is a static class, you should not be constructing it here it!private function dbaccess(){ dbaccess::$db= new mysqli("localhost",USER,PASSWD,DB); if(mysqli_connect_errno()){ echo "no way"; }}public static function GetDb(){if(dbaccess::$db==null){dbaccess::$db= new dbaccess(); } return dbaccess::$db;}} $db=dbaccess::GetDE(); $db->query(..................); will fail...with Call to undefined method dbaccess::query() apparently $db is of type dbaccess... and thus has not does not have query implemented.... any hhelp appreciated..... JCG