php 单例 基类,php继承单例类实现各子类的单例

父类不能被实例化,不能给覆盖。子类实现单例不能使用self,而是用static,它们都是在类体内调用类的方式,区别在于self关键字是在编译时决定它所指代的类,它写在了哪个类中,它指代的就是那个类。而static关键字则是在执行的过程中才决定它所指代的类。

abstract class father{

final protected function __construct(){

$this->init();

}

final protected function __clone(){}

protected function init(){}

//abstract protected function init();

public static function getInstance(){

if(static::$instance === null){

static::$instance = new static();

}

return static::$instance;

}

}

子类声明$instance静态属性,它们从属于各个子类,在父类的getIntance方法中,通过static关键字,调用子类并实例化,然后又赋给子类静态属性$instance。这样就可以实现将获取单例的函数封装在父类的目的。修改子类代码如下:

class Son1 extends Father{

protected static $instance = null;

...

}

class Son2 extends father{

protected static $instance = null;

....

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值