本文實(shí)例講述了PHP實(shí)現(xiàn)一個(gè)限制實(shí)例化次數(shù)的類。分享給大家供大家參考,具體如下:
實(shí)現(xiàn)思路
定義一個(gè)static變量$count,用于保存實(shí)例化對(duì)象的個(gè)數(shù) 定義一個(gè)static方法create,通過(guò)該方法判斷$count的值,進(jìn)而判斷是否進(jìn)一步實(shí)例化對(duì)象。 定義構(gòu)造函數(shù),$count+1 定義析構(gòu)函數(shù),$count-1實(shí)現(xiàn)代碼
<?phpclass 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");
運(yùn)行結(jié)果:
create one
create two
destory two
create three
destory three
destory one
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語(yǔ)法入門教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門教程》及《php常見數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選