PHP单例模式防继承与防克隆实现
本文将详细解析PHP中的单例模式实现方法,通过具体代码示例展示如何构建一个安全的单例类。重点说明在PHP环境下,如何有效阻止子类继承以及对象克隆操作,从而确保类实例的全局唯一性和安全性。
<?php
//单列模式
// //1.普通类
// class singleton{
// }
// $s1 = new singleton();
// $s2 = new singleton();
// //注意,2个变量是同1个对象的时候才全等
// if ($s1 === $s2) {
// echo '是一个对象';
// }else{
// echo '不是一个对象';
// }
// //2.封锁new操作
// class singleton{
// protected function __construct(){}
// }
// $s1 = new singleton();//PHP Fatal error: Call to protected singleton::__construct()
// //3.留个接口来new对象
// class singleton{
// protected function __construct(){}
// public static function getIns(){
// return new self();
// }
// }
// $s1 = singleton::getIns();
// $s2 = singleton::getIns();
// if ($s1 === $s2) {
// echo '是一个对象';
// }else{
// echo '不是一个对象';
// }
// //4.getIns先判断实例
// class singleton{
// protected static $ins = null;
// private function __construct(){}
// public static function getIns(){
// if (self::$ins === null) {
// self::$ins = new self();
// }
// return self::$ins;
// }
// }
// $s1 = singleton::getIns();
// $s2 = singleton::getIns();
// if ($s1 === $s2) {
// echo '是一个对象';
// }else{
// echo '不是一个对象';
// }
// //继承
// class A extends singleton{
// public function __construct(){}
// }
// echo '
';
// $s1 = new A();
// $s2 = new A();
// if ($s1 === $s2) {
// echo '是同一个对象';
// }else{
// echo '不是同一个对象';
// }
// //5.防止继承时被修改了权限
// class singleton{
// protected static $ins = null;
// //方法加final则方法不能被覆盖,类加final则类不能被继承
// final private function __construct(){}
// public static function getIns(){
// if (self::$ins === null) {
// self::$ins = new self();
// }
// return self::$ins;
// }
// }
// $s1 = singleton::getIns();
// $s2 = singleton::getIns();
// if ($s1 === $s2) {
// echo '是同一个对象';
// }else{
// echo '不是同一个对象';
// }
// //继承
// // class A extends singleton{
// // public function __construct(){}
// // }
// //Cannot override final method singleton::__construct()
// echo '';
// $s1 = singleton::getIns();
// $s2 = clone $s1;
// if ($s1 === $s2) {
// echo '是同一个对象';
// }else{
// echo '不是同一个对象';
// }
//6.防止被clone
class singleton{
protected static $ins = null;
//方法加final则方法不能被覆盖,类加final则类不能被继承
final private function __construct(){}
public static function getIns(){
if (self::$ins === null) {
self::$ins = new self();
}
return self::$ins;
}
// 封锁clone
final private function __clone(){}
}
$s1 = singleton::getIns();
$s2 = clone $s1; //Call to private singleton::__clone() from context
if ($s1 === $s2) {
echo '是同一个对象';
}else{
echo '不是同一个对象';
}
希望上述关于PHP单例模式的讲解与代码示例,能帮助开发者更好地理解并应用这一经典设计模式,提升程序设计的规范性与稳定性。