詳解PHP單例模式之繼承碰見的問題

黄舟
發布: 2023-03-06 16:50:01
原創
2384 人瀏覽過

詳解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中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!