详解PHP单例模式之继承碰见的问题
<?php // 单例模式之继承 class Singleton { protected static $ins = null; private final function construct() { } protected final function clone() { } // public static function getIns() { // if(self::$ins === null){ // self::$ins = new self(); // } // return self::$ins; // } public static function getIns() { if(static::$ins === null){ static::$ins = new static(); } return static::$ins; } } class Child extends Singleton { // protected static $ins = null; } /* 输出结果为: bool(true) object(Singleton)#1 (0) { } 问题:对象 $c1, $c2 竟然都是 Singleton 的实例 ??? 解决方法:将 getIns() 方法中关键字 self 替换为 static, 利用后期静态绑定的特性 */ $c1 = Child::getIns(); $c2 = Child::getIns(); var_dump($c1 === $c2); //true var_dump($c1); // ------------------------------------------------------------------------ // 另一个问题 /* 输出结果为: bool(true) object(Child)#1 (0) { } 问题:对象 $c3 竟然是 Child 的实例, 实际上应该是 Singleton 的实例 ??? 原因:因为 $ins 属性是从父类 Singleton 继承过来的, 当第一次调用 Child::getIns() 时, $ins = new Child() 当再次调用 Singleton::getIns() 时, $ins 已经被实例过了, 而且指向 Child 的实例, 所以此时 $c3 变成了 Child 的实例 解决方法:在 Child 类中, 声明自己独有的 $ins 属性 */ $c3 = Singleton::getIns(); var_dump($c1 === $c3); var_dump($c3);
后期静态绑定的 getIns() 方法还会有一个问题:
若 Singleton 的 $ins 属性被设置为 private 的,子类 Child 必须设置自己的 $ins 属性,
因为 static::$ins 优先寻找子类自己的 $ins 属性,但由于子类没有声明且父类的不能继承,此时调用 Child::getIns()
方法便会报错:
Fatal error: Cannot access property Child::$ins in D:\wamp\www\mycode\DesignPattern\Singleton.php on line 27
解决方法:
将父类 Singleton 的 $ins 属性设置为 protected 的 或者 设置子类 Child 自己的 $ins 属性
以上是详解PHP单例模式之继承碰见的问题的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

PHP 8.4 带来了多项新功能、安全性改进和性能改进,同时弃用和删除了大量功能。 本指南介绍了如何在 Ubuntu、Debian 或其衍生版本上安装 PHP 8.4 或升级到 PHP 8.4

CakePHP 是 PHP 的开源框架。它的目的是使应用程序的开发、部署和维护变得更加容易。 CakePHP 基于类似 MVC 的架构,功能强大且易于掌握。模型、视图和控制器 gu

登录 CakePHP 是一项非常简单的任务。您只需使用一项功能即可。您可以记录任何后台进程(如 cronjob)的错误、异常、用户活动、用户采取的操作。在 CakePHP 中记录数据很容易。提供了 log() 函数
