PHP實現(xiàn)一個限制實例化次數(shù)的類示例
本文實例講述了PHP實現(xiàn)一個限制實例化次數(shù)的類。分享給大家供大家參考,具體如下:
實現(xiàn)思路
- 定義一個static變量$count,用于保存實例化對象的個數(shù)
- 定義一個static方法create,通過該方法判斷$count的值,進而判斷是否進一步實例化對象。
- 定義構造函數(shù),$count+1
- 定義析構函數(shù),$count-1
實現(xiàn)代碼
<?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相關內容感興趣的讀者可查看本站專題:《php面向對象程序設計入門教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。
相關文章
PHP使用preg_split和explode分割textarea存放內容的方法分析
這篇文章主要介紹了PHP使用preg_split和explode分割textarea存放內容的方法,結合實例形式分析preg_split和explode函數(shù)的功能、使用技巧與文本字符串分割過程中的相關注意事項,需要的朋友可以參考下2017-07-07
PHP字符轉義相關函數(shù)小結(php下的轉義字符串)
PHP字符轉義相關函數(shù)小結,有時候為了安全起見,我們需要對用戶輸入的字符串進行轉義2007-04-04

