RE: green bean question on singleton php5

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

 



> -----Original Message-----
> From: Julian [mailto:julcol33@xxxxxxxx]
> Sent: Wednesday, January 16, 2008 3:39 PM
> Cc: php-general@xxxxxxxxxxxxx
> Subject: Re:  green bean question on singleton php5
> 
> 
> nope... only works if I change
> 
> $dummy= new dbaccess();
> 
> and keep the rest .....
> 
> Thanks.
> 
> 
> ... hope it does not repeat... got undelivered...
> 
> Eric Butera wrote:
> > On Jan 16, 2008 12:57 PM, julian <correojulian33-php@xxxxxxxx> 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.....
> >>
> >> JCG
> >>
> >> --
> >> PHP General Mailing List (http://www.php.net/)
> >> To unsubscribe, visit: http://www.php.net/unsub.php
> >>
> >>
> >>
> >
> > Try changing dbaccess to self inside the class.
> >
> > Look at this:
> > http://us.php.net/manual/en/language.oop5.patterns.php
> > Example#2 Singleton Function
> >
> >

Not the ideal solution, but this is what I meant:

class dbaccess {

  private static $db = null;
	  
  public static function GetDb() {
    if (!isset(self::$db)) {
	self::$db = new mysqli("localhost", USER, PASSWD, DB);
    	if(mysqli_connect_errno()) {
    	  die("Very bad, you need to handle errors better");
	}
    }
    return self::$db;
  }
}
	
$db = dbaccess::GetDb();
$stmt = $db->query('SHOW DATABASES');

print_r($stmt); // Outputs "mysqli_result Object ( )"

Regards,

Rob

Andrés Robinet | Lead Developer | BESTPLACE CORPORATION
5100 Bayview Drive 206, Royal Lauderdale Landings, Fort Lauderdale, FL 33308
| TEL 954-607-4207 | FAX 954-337-2695
Email: info@xxxxxxxxxxxxx  | MSN Chat: best@xxxxxxxxxxxxx  |  SKYPE:
bestplace |  Web: http://www.bestplace.biz | Web: http://www.seo-diy.com

-- 
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