Home  >  Article  >  Backend Development  >  Examples of how to write singleton classes in PHP, examples of how to write PHP classes_PHP tutorial

Examples of how to write singleton classes in PHP, examples of how to write PHP classes_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 09:48:421007browse

Examples of how to write singleton classes in PHP, examples of how to write PHP classes

The single instance classes in PHP are still very meaningful in terms of data exchange and memory saving. Write a simple example.
Class 1, the single instance class itself:

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;
  }
}

Category 2, application class using the aforementioned single instance class:

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:

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 is the place to call:

$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());

Last display result:

string'SINGLEA CHANGED: ' (length=17)
int110
string'SINGLEB CHANGED: ' (length=17)
int-400

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1022311.htmlTechArticleExamples of how to write singleton classes in PHP, examples of how to write PHP classes Single instance classes in PHP are exchanging data, It still makes sense to save memory. Write a simple example. Class 1, the single instance class itself...
Statement:
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