Home > Article > Backend Development > Examples of how to write singleton classes in PHP, examples of how to write PHP classes_PHP tutorial
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