ホームページ  >  記事  >  バックエンド開発  >  PHP シングルトン モードの簡単なコードの紹介

PHP シングルトン モードの簡単なコードの紹介

黄舟
黄舟オリジナル
2017-03-16 09:12:381466ブラウズ

PHPシングルケースモード簡単なコードの紹介

<?php
// 单例模式

class Singleton
{
	protected static $ins = null;

	/**
	 * 禁止子类重载 construct() 构造方法
	 */
	private final function construct() {
		// 禁止 new
	}

	/**
	 * 禁止子类重载 clone() 方法
	 */
	protected final function clone() {
		// 禁止 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;
	}
}

$obj1 = Singleton::getIns();
$obj2 = Singleton::getIns();
var_dump($obj1 === $obj2); //true
// $obj3 = clone $obj1; //不能被克隆

以上がPHP シングルトン モードの簡単なコードの紹介の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。