开发者

How do I throw an error for my singleton class?

This is the singleton pattern also named as the singleton class. Its goal is to allow only one object of type singleton. If there is already one and I call it, I'd like it to error out in some way. This won't happen in production but in development. Is there a better way then just saying echo echo "Error:only one connection";

class singleton
  {
  protected static $_db_pointer = NULL;
  private function __construct()
    {
    $this->_db_pointer = mysql_connect(DB_HOST, DB_USER, DB_PASS);
    mysql_select_db(DB_DAT开发者_如何转开发ABASE);
    }
  public static function get_instance()
    {
    if(self::$_db_pointer == NULL)
      {
      return new self();
      } 
    else
      {
      echo "Error:only one connection";
      }
    }
  }


Exceptions usually are better.

else
{
  throw new Exception("Error:only one connection");
}

You can also use "LogicException", "RuntimeException", and a few others.

Further reading: http://www.php.net/manual/en/language.exceptions.php

Another approach with singleton class is just to return the object instead of creating a new instance if one exists.


You haven't implemented the singleton pattern correctly. Had you done so, the error condition to which you refer could not exist.

Combining the PHP documentation's singleton example and the original code gives:

class singleton
{
    // Hold an instance of the class
    private static $instance;
    private static $db_pointer;

    // A private constructor; prevents direct creation of object
    private function __construct() {
        $this->_db_pointer = mysql_connect(DB_HOST, DB_USER, DB_PASS);
        mysql_select_db(DB_DATABASE);        
    }

    // The singleton method
    public static function get_instance() 
    {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }

        return self::$instance;
    }

    public function getDbPointer() {
        return self::$db_pointer;
    }


    // Prevent users to clone the instance
    public function __clone() {
        trigger_error('Clone is not allowed.', E_USER_ERROR);
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜