Re: green bean question on singleton php5

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Jan 16, 2008 1:36 PM, Julian <julcol33@xxxxxxxx> 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

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux