Learn PHP design pattern singleton pattern
Release: 2016-07-25 09:05:17
Original
783 people have browsed it
-
-
/** - * PHP design pattern singleton mode
- * $_instance must be declared as a static private variable
- * The constructor and destructor must be declared private to prevent external programs from creating new
- * classes and thereby losing the meaning of the singleton mode
- * getInstance The () method must be set to public, and this method must be called
- * to return a reference to the instance
- *:: The operator can only access static variables and static functions
- * new objects will consume memory
- * Usage scenarios: the most commonly used The place is the database connection.
- * After using the singleton pattern to generate an object,
- * the object can be used by many other objects.
- * @link http://bbs.it-home.org
- */
class Danli {
- //Static member variables that save class instances
- private static $ _instance;
- //Construction method of private tag
- private function __construct(){
- echo 'This is a Constructed method;';
- }
-
- //Create __clone method to prevent the object from being copied and cloned
- public function __clone(){
- trigger_error('Clone is not allow!',E_USER_ERROR);
- }
//Single instance method, a public static method used to access the instance
- public static function getInstance(){
- if(!(self::$_instance instanceof self)){
- self::$_instance = new self;
- }
return self::$_instance;
- }
public function test(){
- echo 'Calling method successfully';
- }
- }
//Classes that use new to instantiate the private mark constructor will report an error
- // $danli = new Danli();
- //The correct method is to use the double colon::operator to access the static method to obtain the instance
- $danli = Danli::getInstance();
- $danli->test();
- // Copying (cloning) the object will result in an E_USER_ERROR
- $danli_clone = clone $danli;
- ?>
-
Copy code
|
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
Latest Articles by Author
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31