Home > Backend Development > PHP Tutorial > Learn PHP design pattern singleton pattern

Learn PHP design pattern singleton pattern

WBOY
Release: 2016-07-25 09:05:17
Original
791 people have browsed it
  1. /**

  2. * PHP design pattern singleton mode
  3. * $_instance must be declared as a static private variable
  4. * The constructor and destructor must be declared private to prevent external programs from creating new
  5. * classes and thereby losing the meaning of the singleton mode
  6. * getInstance The () method must be set to public, and this method must be called
  7. * to return a reference to the instance
  8. *:: The operator can only access static variables and static functions
  9. * new objects will consume memory
  10. * Usage scenarios: the most commonly used The place is the database connection.
  11. * After using the singleton pattern to generate an object,
  12. * the object can be used by many other objects.
  13. * @link http://bbs.it-home.org
  14. */

  15. class Danli {

  16. //Static member variables that save class instances
  17. private static $ _instance;
  18. //Construction method of private tag
  19. private function __construct(){
  20. echo 'This is a Constructed method;';
  21. }
  22. //Create __clone method to prevent the object from being copied and cloned
  23. public function __clone(){
  24. trigger_error('Clone is not allow!',E_USER_ERROR);
  25. }

  26. //Single instance method, a public static method used to access the instance

  27. public static function getInstance(){
  28. if(!(self::$_instance instanceof self)){
  29. self::$_instance = new self;
  30. }

  31. return self::$_instance;

  32. }

  33. public function test(){

  34. echo 'Calling method successfully';
  35. }
  36. }

  37. //Classes that use new to instantiate the private mark constructor will report an error

  38. // $danli = new Danli();
  39. //The correct method is to use the double colon::operator to access the static method to obtain the instance
  40. $danli = Danli::getInstance();
  41. $danli->test();
  42. // Copying (cloning) the object will result in an E_USER_ERROR
  43. $danli_clone = clone $danli;
  44. ?>

Copy code


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template