search

Home  >  Q&A  >  body text

php - Singleton pattern problem

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!

我想大声告诉你我想大声告诉你2830 days ago630

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-05-16 13:16:53

    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() ;  //调用对象私有方法连接 数据库
    }

    reply
    0
  • 迷茫

    迷茫2017-05-16 13:16:53

    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

    reply
    0
  • Cancelreply