tags:

views:

59

answers:

1

Hi, i'm using DbSimple, but there is some code which i could write into another module. Here is it's code:

<?php

require_once 'config.php';
require_once 'DbSimple/Generic.php';

class MysqlWorker
{
    private static $instance = NULL;

    public function getInstance()
    {
        if( self::$instance == NULL )
        {
            self::$instance = new MysqlWorker();
        }
        return self::$instance;
    }

    private function __construct() 
    {
        self::$instance = DbSimple_Generic::connect( 'mysql://'.MYSQL_USER.':'.MYSQL_PASS.'@'.MYSQL_HOST.'/'.MYSQL_DB.'' ); 
        self::$instance->setErrorHandler( 'mysqlErrorHandler' ); 
        self::$instance->query( "SET NAMES 'utf8'" ); 
    }                                                                                                                                                                                     

    private function mysqlErrorHandler( $message, $info )
    {
        if ( !error_reporting()) return;
        echo "Database error: $message<br><pre>";
            print_r($info);
        echo "</pre>";
        exit();
    }

    private function __clone() {}
}
?>

When i added code into class constructor:

var_dump( self::$instance );

I got:

object(DbSimple_Mysql)#2 (17) { ...}

So, there is everything is clear. But when i'm using code in another location:

require_once 'modules/mysql_worker.php';

var_dump( MysqlWorker::getInstance() );

The result is:

object(MysqlWorker)#1 (0) { }

Why does MysqlWorker::getInstance object is empty?

A: 

Both the constructor and the static function getInstance assign something to the static property MysqlWorker::$instance.

class MysqlWorker
{
    private static $instance = NULL;
    private $connection = NULL;

    public function getInstance()
    {
     if( self::$instance == NULL )
     {
          self::$instance = new MysqlWorker();
     }
     return self::$instance;
    }

    private function __construct()
    {
     $this->connection = DbSimple_Generic::connect( 'mysql://'.MYSQL_USER.':'.MYSQL_PASS.'@'.MYSQL_HOST.'/'.MYSQL_DB.'' );
     $this->connection->setErrorHandler( array($this,'mysqlErrorHandler') );
     $this->connection->query( "SET NAMES 'utf8'" );
    }
VolkerK
Thanks, it was my problem. But you have an error in your code. We can't refer to non-static objects by self.
Ockonal
fixed. Btw: `SET NAMES utf8` may "confuse" the client lib esp. mysql_real_escape_string (if DbSimple uses it). See http://php.net/mysql_set_charset
VolkerK