前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >PHP单例模式实例分析【防继承,防克隆操作】

PHP单例模式实例分析【防继承,防克隆操作】

作者头像
砸漏
发布2020-10-21 09:55:29
1.2K0
发布2020-10-21 09:55:29
举报
文章被收录于专栏:恩蓝脚本

本文实例讲述了PHP单例模式。分享给大家供大家参考,具体如下:

代码语言:javascript
复制
<?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 '<br ';
// $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 '<hr ';
// $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 '不是同一个对象';
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档