php - How can I restrict user to only created limited numbers of objects -
<?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(); ?>
how can restrict user created limited numbers of objects. above example if create 1 more object throw error.
add static counter variable class, add constructor , destructor increase , decrease it. check value in constructor:
<?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();
script output:
englishscience fatal error: uncaught exception 'exception' 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
Comments
Post a Comment