DarkLeafyGreen
DarkLeafyGreen

Reputation: 70416

PHP singelton class for PDO connection

I have designed following class

<?php 

    class DB { 

        private static $objInstance; 

        /* 
         * Class Constructor - Create a new database connection if one doesn't exist 
         * Set to private so no-one can create a new instance via ' = new DB();' 
         */ 
        private function __construct() {} 

        /* 
         * Like the constructor, we make __clone private so nobody can clone the instance 
         */ 
        private function __clone() {} 

        /* 
         * Returns DB instance or create initial connection 
         * @param 
         * @return $objInstance; 
         */ 
        public static function getInstance(  ) { 

            if(!self::$objInstance){ 

                $ini_array = parse_ini_file("db.ini");

                $dbInfo['server'] = $ini_array['server'];
                $dbInfo['database'] = $ini_array['database'];
                $dbInfo['username'] = $ini_array['username'];
                $dbInfo['password'] = $ini_array['password'];

                $dsn = 'mysql:host='.$dbInfo['server'].';dbname='.$dbInfo['database'].'';

                self::$objInstance = new PDO(DB_DSN, $dbInfo['username'], $dbInfo['password']); 
                self::$objInstance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
            } 

            return self::$objInstance; 

        } # end method 

        /* 
         * Passes on any static calls to this class onto the singleton PDO instance 
         * @param $chrMethod, $arrArguments 
         * @return $mix 
         */ 
        final public static function __callStatic( $chrMethod, $arrArguments ) { 

            $objInstance = self::getInstance(); 

            return call_user_func_array(array($objInstance, $chrMethod), $arrArguments); 

        } # end method 

    }
?>

My problem is when I want to perform a query I get following error:

Fatal error: Call to undefined method DB::query()

foreach(DB::query("SELECT * FROM content_type_video") as $row){ 
    print_r($row); 
}

Any ideas why and how to fix this?

Upvotes: 2

Views: 1500

Answers (2)

hakre
hakre

Reputation: 197767

The functionality you want to make use of is not available in your PHP version - you need to upgrade to at least PHP 5.3 for __callStatic.

However I suggest you to stop using singletons anyway and stop using static function calls everywhere in your code.

Upvotes: 1

MrCode
MrCode

Reputation: 64526

$db = DB::getInstance();

foreach($db->query("SELECT * FROM content_type_video") as $row){ 
    print_r($row); 
}

Upvotes: 1

Related Questions