php - Singleton pattern problem
我想大声告诉你
我想大声告诉你 2017-05-16 13:14:53
0
2
552

Today I tried to write a singleton pattern, and then instantiated the singleton object twice and var_dumped it out respectively. Now the first result is null, and the second one shows the object type. What is going on? Thank you, teachers. Take a look, thank you!

我想大声告诉你
我想大声告诉你

reply all(2)
小葫芦

You should put the returned singleton object outside the if judgment, otherwise the object cannot be returned when the object is not created for the first time
static public function GetConnec()

{
        if(!self::$instance instanceof self)
        {
            self::$instance =new self;//若当前对象实例不存在
        }
        $temp=self::$instance; //获取当前单例
        return $temp::Con() ;  //调用对象私有方法连接 数据库
}
迷茫

The first call does not return the new object, so it is null. The second call to singleton. Since an object has been instantiated the first time, the object instantiated for the first time is returned, and the value is returned for the second time. , the return value is the object instantiated by the first call

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template