PHP里的单例类写法实例

这篇文章主要介绍了PHP里的单例类写法实例,本文直接给出代码实例,需要的朋友可以参考下,PHP里的单实例类在进行数据交换,节省内存上还是很有意义的,写个简单例子。

类1,单实例类本身:

  1. class UTIL {
  2. private static $instance;
  3. public function get() {
  4. if (!self::$instance) {
  5. self::$instance = new UTIL();
  6. }
  7. return self::$instance;
  8. }
  9. public $number = 10;
  10. public function change($num) {
  11. $this->number += $num;
  12. }
  13. public function getNum() {
  14. return $this->number;
  15. }
  16. }

类2,使用前述单实例类的应用类:

  1. class SINGLEA {
  2. private $numInst;
  3. function __construct() {
  4. $this->numInst = UTIL::get();
  5. }
  6. public function change($num) {
  7. $this->numInst->change($num);
  8. }
  9. public function getNum() {
  10. return $this->numInst->getNum();
  11. }
  12. }

类3,同类2:

  1. class SINGLEB {
  2. private $numInst;
  3. function __construct() {
  4. $this->numInst = UTIL::get();
  5. }
  6. public function change($num) {
  7. $this->numInst->change($num);
  8. }
  9. public function getNum() {
  10. return $this->numInst->getNum();
  11. }
  12. }

最后是调用的地方:

  1. $instA = new SINGLEA();
  2. $instA->change(100);
  3. var_dump('SINGLEA CHANGED: ');
  4. var_dump($instA->getNum());
  5. $instB = new SINGLEB();
  6. $instB->change(-510);
  7. var_dump('SINGLEB CHANGED: ');
  8. var_dump($instB->getNum());

最后的显示结果:

  1. string'SINGLEA CHANGED: ' (length=17)
  2. int110
  3. string'SINGLEB CHANGED: ' (length=17)
  4. int-400