使用PHP怎么实现一个限制实例化次数的类

使用PHP怎么实现一个限制实例化次数的类

使用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

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对亿速云的支持。