Re: green bean question on singleton php5
| From: | Nathan Nobbe | Date: | Wed, 16 Jan 2008 18:59:57 +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-267431@lists.php.net to get a copy of this message | ||
On Jan 16, 2008 1:36 PM, Julian <julcol33@yahoo.es> wrote:
> I would like to understand what am I missing fom the concept....
here are the issues i see;
you should have a private static for the instance of dbaccess
you should have a private instance variable for the instance of the mysqli
class
you should be able to programatically handle failure to connect to the
database
in the code i show here, you do not have to return the mysqli instance from
dbaccess::GetDb()
if you prefer, that method would return the instance to the singleton, then
you would
have a public accessor method that would return the instance of the mysqli
class.
this is the simpler of the 2 options.
class dbaccess{
private static $instance = null; // instance of dbaccess
public static $othervar=33; // dont know what this is for, but you
can keep it if you want
private $mySqliConn = null; // instance of mysqli
private function dbaccess() {
$this->mySqliConn = new mysqli("localhost",USER,PASSWD,DB);
if(mysqli_connect_errno()) {
throw new RuntimeException(mysqli_connect_error());
}
}
public static function GetDb(){
if(dbaccess::$instance == null) {
dbaccess::$instance = new dbaccess();
}
return $this->mySqliConn;
}
}
-nathan