<?php
class Book
{
var $name;
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();
?>
如何将用户限制为仅创建有限数量的对象。对于上面的例子,如果我将再创建一个对象,那么我将抛出一个错误。
答案 0 :(得分:2)
将静态计数器变量添加到您的类中,添加构造函数和析构函数以增加和减少它。检查构造函数中的值:
<?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 :(得分:1)
解决方案是:
Book
类private
。$number_of_objects
和$threshold_number_of_objects
的成员。getInstance()
方法来创建Book
类的新实例。如果已创建的对象数小于阈值,则此getInstance()
方法将创建类Book
的新实例,否则将返回错误。所以你的代码应该是这样的:
class Book{
private $name;
private static $number_of_objects = 0;
private static $threshold_number_of_objects = 2;
// Since it's constructor method is private
// it prevents objects from being created from
// outside of the class
private function __construct(){}
// It creates an object if the number of objects
// already created is less than the threshold value
public static function getInstance() {
if(self::$number_of_objects < self::$threshold_number_of_objects){
++self::$number_of_objects;
return new Book();
}else{
echo "Error: Number of objects crossed the threshold value";
return false;
}
}
public function setName($name){
$this->name = $name;
}
public function getName(){
return $this->name ;
}
}
//$objectfirst = new Book; invalid
$objectfirst = Book::getInstance();
if($objectfirst){
$objectfirst->setName('English');
echo $objectfirst->getName() . "<br />";
}
//$objectsecond = new Book; invalid
$objectsecond = Book::getInstance();
if($objectsecond){
$objectsecond->setName('Science');
echo $objectsecond->getName() . "<br />";
}
//$objectthird = new Book; invalid
$objectthird = Book::getInstance();
if($objectthird){
$objectthird->setName('Engineering');
echo $objectthird->getName() . "<br />";
}
输出:
English
Science
Error: Number of objects crossed the threshold value