Home  >  Article  >  Backend Development  >  Example of php singleton pattern

Example of php singleton pattern

WBOY
WBOYOriginal
2016-07-25 09:10:201132browse
  1. /**

  2. * by bbs.it-home.org
  3. * 2012-12-26
  4. */
  5. class Mysql{
  6. //This attribute is used to save the instance
  7. private static $conn;
  8. //The constructor is private, Prevent the creation of objects
  9. private function __construct(){
  10. $this->conn = mysql_connect('localhost','root','');
  11. }
  12. //Create a method for instantiating objects
  13. public static function getInstance(){
  14. if(!(self::$conn instanceof self)){
  15. self::$conn = new self;
  16. }
  17. return self::$conn;
  18. }
  19. //Prevent the object from being copied
  20. public function __clone(){
  21. trigger_error('Clone is not allowed!');
  22. }

  23. }

  24. //You can only get the instance in this way, not new and clone
  25. $mysql = Mysql:: getInstance();
  26. ?>

Copy code



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn