添加靜態計數器變量到您的類,添加構造函數和析構函數來增加和減少它。檢查值在構造函數中:
<?php
class Book
{
var $name;
private static $counter=0;
function __construct()
{
self::$counter++;
if(self::$counter > 2)
throw new Exception('Limit exceeded');
}
function __destruct()
{
self::$counter--;
}
function setName($name){
$this->name = $name;
}
function getName(){
return $this->name ;
}
}
$objectfirst = new Book;
$objectfirst->setName('English');
echo $objectfirst->getName();
$objectsecond = new Book;
$objectsecond->setName('Science');
echo $objectsecond->getName();
$objectthird = new Book;
$objectthird->setName('Test');
echo $objectthird->getName();
腳本輸出:
EnglishScience
Fatal error: Uncaught exception 'Exception' with message 'Limit exceeded' in sandbox/scriptname.php:12
Stack trace:
#0 sandbox/scriptname.php(36): Book->__construct()
#1 {main}
thrown in sandbox/scriptname.php on line 12
另一種方法是創建一個單獨的類,這樣可以確保始終有類的1個實例從不2 。 – Daan
你的情況應該是什麼限制? 2個對象? – RomanPerekhrest
在我的情況下,它不應該超過2。 – Rajiv