RE: Problems with Database Singleton Class

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

 



Thank You!

Yep, moving the DB creation logic into the getInstance method did the
trick.

I now have one instance of my DB connection to use throughout my
program.

New and improved (working) getInstance method:

/**
 * Return DB instance or create intitial connection
 * @return object (PDO)
 * @access public
 */
public static function getInstance() {

  if (!self::$instance) {
    $settings = new Settings();
    self::$instance = new PDO($db, $settings->id[$db],
$settings->pwd[$db]);
    self::$instance->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
  }
    return self::$instance;
}


Ken Vandegrift

-----Original Message-----
From: Martin Vidovic [mailto:martinv@xxxxxxxxxxxxx] 
Sent: Friday, April 14, 2006 10:58 AM
To: php-windows@xxxxxxxxxxxxx
Subject: Re:  Problems with Database Singleton Class

On Friday 14 of April 2006 17:51, Vandegrift, Ken wrote:
> class WebDBConn {
>
>   private static $instance = NULL;
>
>   private function __construct() {
>
>     self::$instance = new PDO($db, $user, $pwd);
>     self::$instance->setAttribute(PDO::ATTR_ERRMODE,
> PDO::ERRMODE_EXCEPTION);
>   }
>
>   public static function getInstance() {
>
>     if (!self::$instance) {
>       self::$instance = new WebDBConn;
Here you overwrite your instance of PDO class with WebDBConn instance.
>     }
>     return self::$instance;
>   }
> }

What you should do, is put the $instance initialization which you have
in __construct(), to the getInstance() method in place of
'self::$instance = new WebDBConn'.
__construct() can be empty as you do not need an instance of WebDBConn
(everything is static).

Martin

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

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



[Index of Archives]     [PHP Home]     [PHP Users]     [PHP Database Programming]     [PHP Install]     [Kernel Newbies]     [Yosemite Forum]     [PHP Books]

  Powered by Linux