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

WBOY
Release: 2016-07-13 09:48:42
Original
1010 people have browsed it

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;
  }
}
Copy after login

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

Copy after login

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

Copy after login

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

Copy after login

Last display result:

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

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...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!