Singleton pattern in php

前端 未结 4 1091
-上瘾入骨i
-上瘾入骨i 2020-12-10 21:04
class SingleTon
{
    private static $instance;

    private function __construct()
    {
    }

    public function getInstance() {
        if($instance === null) {         


        
4条回答
  •  天命终不由人
    2020-12-10 21:31

    Yes, you have to call using

    SingleTon::getInstance();
    

    The first time it will test the private var $instance which is null and so the script will run $instance = new SingleTon();.

    For a database class it's the same thing. This is an extract of a class which I use in Zend Framework:

    class Application_Model_Database
    {
       /**
        *
        * @var Zend_Db_Adapter_Abstract
        */
       private static $Db = NULL;
    
       /**
        *
        * @return Zend_Db_Adapter_Abstract
        */
       public static function getDb()
       {
          if (self::$Db === NULL)
             self::$Db = Zend_Db_Table::getDefaultAdapter();
          return self::$Db;
       }
    }
    

    Note: The pattern is Singleton, not SingleTon.

提交回复
热议问题