php防止一个类实例化,PHP实现一个限制实例化次数的类示例

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

实现思路

定义一个static变量$count,用于保存实例化对象的个数

定义一个static方法create,通过该方法判断$count的值,进而判断是否进一步实例化对象。

定义构造函数,$count+1

定义析构函数,$count-1

实现代码

class demo{

public $name;

public static $count=0;

private function __construct($name){

echo "create $name
";

$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

希望与广大网友互动??

点此进行留言吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值