Singletons ve DbSimple

1 Cevap php

Ben DbSimple kullanıyorum, ama başka bir modülün içine yazabilirsiniz bazı kod var. İşte bu kod olduğunu:

<?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() {}
}
?>

I sınıf yapıcı içine kodu eklendiğinde:

var_dump( self::$instance );

I got:

nesne (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() );

Sonuç:

nesne (MysqlWorker) # 1 (0) {}

Neden MysqlWorker::getInstance nesne boş geliyor?

1 Cevap

Yapıcı ve statik işlev getInstance statik özelliği şey atamak Hem 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'" );
    }