PHP 单例模式继承的实现方式
Posted ﹏Sakura
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 单例模式继承的实现方式相关的知识,希望对你有一定的参考价值。
/** * @author xiaojiang * 方式1 */ class father{ static $models = []; static public function getInstance(){ $name = get_called_class(); if( !isset( self::$models[$name] ) ){ self::$models[$name] = new $name(); } return self::$models[$name]; } public function m1(){ echo "fm1"; } public function m2(){ echo "fm2"; } } class child extends father{ public function m1(){ echo ‘cm1‘; } } father::getInstance()->m1(); child::getInstance()->m1(); /** * 方式2 */ class base{ static protected $ins = []; static public function getInstance(){ $cName = get_called_class(); if( !isset(static::$ins[$cName]) ){ static::$ins[$cName] = new $cName; } return static::$ins[$cName]; } public function m1(){ return "base m1"; } public function m2(){ return "base m2"; } } class cbase extends base{ //static public $ins = null; static public function getInstance(){ return parent::getInstance(); } public function m1(){ return "cbase m1<br>"; } } echo base::getInstance()->m1()."<br>"; echo cbase::getInstance()->m1();
以上是关于PHP 单例模式继承的实现方式的主要内容,如果未能解决你的问题,请参考以下文章