Examples of Singleton writing in PHP. Examples of Singleton writing in PHP this article mainly introduces examples of Singleton writing in PHP. This article provides code examples directly, for more information about how to write a single instance class in PHP, see examples of writing a single instance class in PHP.
This article mainly introduces examples of singleton class writing in PHP. This article provides code examples directly. For more information, see
Single instance classes in PHP are performing data exchange, which makes sense to save memory. Write a simple example.
Class 1, single instance class itself:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Class UTIL { Private static $ instance; Public function get (){ If (! Self: $ instance ){ Self: $ instance = new UTIL (); } Return self: $ instance; } Public $ number = 10; Public function change ($ num ){ $ This-> number + = $ num; } Public function getNum (){ Return $ this-> number; } } |
Class 2: Application class that uses the aforementioned single instance class:
?
1 2 3 4 5 6 7 8 9 10 11 12 |
Class SINGLEA { Private $ numInst; Function _ construct (){ $ This-> numInst = UTIL: get (); } Public function change ($ num ){ $ This-> numInst-> change ($ num ); } Public function getNum (){ Return $ this-> numInst-> getNum (); } } |
Class 3, similar 2:
?
1 2 3 4 5 6 7 8 9 10 11 12 |
Class SINGLEB { Private $ numInst; Function _ construct (){ $ This-> numInst = UTIL: get (); } Public function change ($ num ){ $ This-> numInst-> change ($ num ); } Public function getNum (){ Return $ this-> numInst-> getNum (); } } |
Finally, it is called:
?
1 2 3 4 5 6 7 8 |
$ InstA = new SINGLEA (); $ InstA-> change (100 ); Var_dump ('singlea CHANGED :'); Var_dump ($ instA-> getNum ()); $ InstB = new SINGLEB (); $ InstB-> change (-510 ); Var_dump ('singleb CHANGED :'); Var_dump ($ instB-> getNum ()); |
The final result is as follows:
?
1 2 3 4 |
String 'singlea CHANGED: '(length = 17) Int110 String 'singleb CHANGED: '(length = 17) Int-400 |
This article introduces examples of singleton class writing in PHP. This article provides code examples. if you need them, you can refer to the number of Singleton classes in PHP...