PHP里的单例类写法实例
程序员文章站
2022-06-15 23:17:18
php里的单实例类在进行数据交换,节省内存上还是很有意义的。写个简单例子。
类1,单实例类本身:
class util {
private static...
php里的单实例类在进行数据交换,节省内存上还是很有意义的。写个简单例子。
类1,单实例类本身:
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; } }
类2,使用前述单实例类的应用类:
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(); } }
类3,同类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(); } }
最后是调用的地方:
$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());
最后的显示结果:
string'singlea changed: ' (length=17) int110 string'singleb changed: ' (length=17) int-400