Heim  >  Artikel  >  Backend-Entwicklung  >  PHP 的单例模式代码

PHP 的单例模式代码

WBOY
WBOYOriginal
2016-07-25 08:46:101064Durchsuche
  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


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn