本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《php数组(array)操作技巧大全》、《php基本语法入门教程》、《php运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家php程序设计有所帮助。