添加静态计数器变量到您的类,添加构造函数和析构函数来增加和减少它。检查值在构造函数中:
<?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