This article mainly introduces a single example class in PHP example, this article directly gives code examples, the need for friends can refer to the
The single instance class in PHP is very meaningful for data exchange, saving 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 ();} ret Urn self:: $instance; Public $number = 10; Public function Change ($num) {$this->number + = $num;} public Function Getnum () {return $this->number;}} |
Class 2, use the application class of the preceding 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, homogeneous 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 ();}} |
Last is the place to call:
?
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 display result:
?
1 2 3 4 |
String ' Singlea CHANGED: ' (length=17) int110 string ' Singleb CHANGED: ' (length=17) int-400 |