PHP如何实现一个限制实例化次数的类?这篇文章主要介绍了PHP实现一个限制实例化次数的类,涉及php面向对象程序设计中静态对象与静态方法的相关使用技巧,下面小编就为大家带来相关的内容,需要的朋友就来一聚教程网参考一下吧!
本文实例讲述了PHP实现一个限制实例化次数的类。分享给大家供大家参考,具体如下:
实现思路
定义一个static变量$count,用于保存实例化对象的个数
定义一个static方法create,通过该方法判断$count的值,进而判断是否进一步实例化对象。
定义构造函数,$count+1
定义析构函数,$count-1
实现代码
";
$this->name = $name;
self::$count++;
}
public function __destruct(){
echo "destory ".$this->name."
";
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