Simple code introduction to PHP singleton mode

黄舟
Release: 2023-03-06 16:52:01
Original
1500 people have browsed it

PHPSimple code introduction to singleton mode

<?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; //不能被克隆
Copy after login

The above is the detailed content of Simple code introduction to PHP singleton mode. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!