详解PHP单例模式之继承碰见的问题

黄舟
发布: 2017-03-16 09:06:44
原创
2706人浏览过

详解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() 

方法便会报错:

立即学习PHP免费学习笔记(深入)”;

AI建筑知识问答
AI建筑知识问答

用人工智能ChatGPT帮你解答所有建筑问题

AI建筑知识问答 22
查看详情 AI建筑知识问答

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中文网其它相关文章!

相关标签:
php
PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号