PHP实现一个限制实例化次数的类示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

PHP实现一个限制实例化次数的类示例

  2021-04-02 我要评论

本文实例讲述了PHP实现一个限制实例化次数的类。分享给大家供大家参考,具体如下:

实现思路

  1. 定义一个static变量$count,用于保存实例化对象的个数
  2. 定义一个static方法create,通过该方法判断$count的值,进而判断是否进一步实例化对象。
  3. 定义构造函数,$count+1
  4. 定义析构函数,$count-1

实现代码

<?php
class demo{
  public $name;
  public static $count=0;
  private function __construct($name){
    echo "create $name <br/>";
    $this->name = $name;
    self::$count++;
  }
  public function __destruct(){
    echo "destory ".$this->name."<br/>";
    self::$count--;
  }
  public static function create($name){
    if(self::$count>2){
      die("you can only create at most 2 objects.");
    }else{
      return new self($name);
    }
  }
}
$one = demo::create("one");
$two = demo::create("two");
$two = null;
$three = demo::create("three");

运行结果:

create one
create two
destory two
create three
destory three
destory one

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

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们