Tutorial on SingletonPattern
- Class DatabaseConnection {
- Private static $ db;
- Private static $ _ handle = null;
- Public static function get (){
- If (self: $ db = null ){
- Echo _ LINE __;
- Self: $ db = new DatabaseConnection ();
- }
- Return self: $ _ handle;
- }
- Private function _ construct (){
- $ Dsn = 'MySQL: // root: password @ localhost/photos ';
- Self: $ _ handle = 123;
- }
- }
- Print ("Handle =". DatabaseConnection: get (). "\ n ");
- Print ("Handle =". DatabaseConnection: get (). "\ n ");
- ?>
9 Handle = 123 Handle = 123 [Finished in 0.1 s]
Example 2: php Singleton mode.
- Class DatabaseConnection
- {
- Public static function get ()
- {
- Static $ db = null; // The static member in Example 1 is changed to a static variable.
- If ($ db = null ){
- Echo _ LINE __;
- $ Db = new DatabaseConnection ();
- }
- Return $ db;
- }
- Private $ _ handle = null; // This parameter indicates static removal of Example 1.
- Private function _ construct ()
- {
- $ Dsn = 'MySQL: // root: password @ localhost/photos ';
- $ This-> _ handle = 123;
- }
- // The method for getting a private member $ _ handle is added here.
- Public function handle ()
- {
- Return $ this-> _ handle;
- }
- }
- Print ("Handle =". DatabaseConnection: get ()-> handle (). "\ n ");
- Print ("Handle =". DatabaseConnection: get ()-> handle (). "\ n ");
- ?>
8 Handle = 123 Handle = 123 [Finished in 0.1 s] the two examples of personal preference for the second 4. Limit the number of instances that can be generated
- Class DatabaseConnection {
- Public static function get ($ persistent_id = 0) {// input an identifier
- Static $ db = array (); // change to array here
- If (! Array_key_exists ($ persistent_id, $ db )){
- Echo _ LINE __;
- $ Db [$ persistent_id] = new DatabaseConnection ();
- }
- Return $ db [$ persistent_id];
- }
- Private $ _ handle = null;
- Private function _ construct (){
- $ Dsn = 'MySQL: // root: password @ localhost/photos ';
- $ This-> _ handle = 123;
- }
- // The method for getting a private member $ _ handle is added here.
- Public function handle (){
- Return $ this-> _ handle;
- }
- }
- Print ("Handle =". DatabaseConnection: get (1)-> handle (). "\ n ");
- Print ("Handle =". DatabaseConnection: get (2)-> handle (). "\ n ");
- Print ("Handle =". DatabaseConnection: get (2)-> handle (). "\ n ");
- ?>
6 Handle = 123 6 Handle = 123 Handle = 123 [Finished in 0.1 s] Supplement: using static methods, we can easily implement the php Singleton mode. You can also use global variable storage, but this method is only applicable to small applications. In large applications, avoid using global variables and use objects and methods to access resources. |