Home  >  Article  >  Backend Development  >  PHP singleton pattern code

PHP singleton pattern code

WBOY
WBOYOriginal
2016-07-25 08:46:101062browse
  1. class User {
  2. static function getInstance()
  3. {
  4. if (self::$instance == NULL) { // If instance is not created yet, will create it.
  5. self::$instance = new User();
  6. }
  7. return self::$instance;
  8. }
  9. private function __construct()
  10. // Constructor method as private so by mistake developer not crate
  11. // second object of the User class with the use of new operator
  12. {
  13. }
  14. private function __clone()
  15. // Clone method as private so by mistake developer not crate
  16. //second object of the User class with the use of clone.
  17. {
  18. }
  19. function Log($str)
  20. {
  21. echo $str;
  22. }
  23. static private $instance = NULL;
  24. }
  25. User::getInstance()->Log("Welcome User");
复制代码

PHP


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