怎么在PHP中利用单例模式实现防继承和防克隆操作

发布时间:2021-06-07 16:40:28 作者:Leah
来源:亿速云 阅读:154

这篇文章给大家介绍怎么在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 '<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 '不是同一个对象';
}

关于怎么在PHP中利用单例模式实现防继承和防克隆操作就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. JavaScript中怎么实现防抖和节流
  2. PHP中怎么实现单例模式

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php

上一篇:怎么在tp5框架中使用tp3.2分页

下一篇:使用PHP制作一个文件上传小程序

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》