Re: green bean question on singleton php5

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

 



julian wrote:
> 
> 
> Hi,
> 
> I am implementing this
> 
> class dbaccess{
>   static $db=null;
>   static $othervar=33;
>     
>   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.....

That's not technically a singletron.

A singltron is a class of which only one instance is permitted.

Here you are trying to mysqli object.

You have two options here. I'll let you take your pick:

1. extend mysqli

class dbaccess extends mysqli {
  private function __construct {
    parent::__construct("localhost",USER,PASSWD,DB);
    if (mysqli_connect_errno()){
      throw Exception('No Way');
    }
  }

  public static function GetDb(){
    static $obj = false;
    if (false === $obj) {
  	$obj = new dbaccess();
    }
    return $obj
  }
}

Or 2. Just create an accessor class

class dbaccess {
  public static function GetDb(){
    static $obj = false;
    if (false === $obj) {
  	$obj = new mysqli("localhost",USER,PASSWD,DB);
        if (mysqli_connect_errno()){
          return false;
        }
    }
    return $obj
  }
}



You call them essentially the same way, but the first one has to use an
exception as the errors are detected in the constructor this will return
an object of type dbaccess (which in turn is an extension of mysqli).

The second is just a static function wrapped in a class (and could be
implemented as a normal function if you prefer - there is no need for a
class really). It will return an object of type mysqli.

Apologies if there are typos or thinkos as I've not run the above.

Col

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[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