Max Frai
Max Frai

Reputation: 64266

PHP and singletons again

class ConfigReader { private static $instance = NULL; protected $configData = array();

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

    public function getConfigValue( $getName )
    {
        echo 'In function';
    }

    private function __construct()
    {
        $this->configData = %READ_FROM_DATABASE%;
    }

    private function __clone() {}
}

And for:

var_dump( ConfigReader::getInstance() )

I got: NULL

I broke by brains... Help me, please.

Upvotes: 2

Views: 194

Answers (3)

Pascal MARTIN
Pascal MARTIN

Reputation: 400932

In the method getInstance, you should use only one '=' : you want to make an assignation, and not a compatison :

self::$instance = new ConfigReader();

Instead of

self::$instance == new ConfigReader();


And that method should be declared as static, as you are using it as a static method :

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

Weth these two modifications, it should work ;-)

Upvotes: 5

rogeriopvl
rogeriopvl

Reputation: 54056

The method getInstance() should also be static.

Upvotes: 5

Xeor
Xeor

Reputation: 1866

Just a typo: self::$instance == new ConfigReader() contains == instead of =

Upvotes: 6

Related Questions