PHP和单身人士再次

时间:2009-09-13 11:20:26

标签: php singleton

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

并且:

var_dump( ConfigReader::getInstance() )

我得到了:NULL

我被大脑打破了......请帮帮我。

3 个答案:

答案 0 :(得分:6)

只是一个错字:self::$instance == new ConfigReader()包含==而不是=

答案 1 :(得分:5)

方法getInstance()也应该是静态的。

答案 2 :(得分:5)

在方法getInstance中,你应该只使用一个'=':你想要进行分配,而不是compatison:

self::$instance = new ConfigReader();

而不是

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


并且该方法应声明为static,因为您将其用作静态方法:

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

Weth这两个修改,它应该工作; - )