oop - PHP - unique attribute for objects of a class -
i have class
class myclass{ private $id; private $name; public function __construct ($id, $name){ $this->name = $name; } } $ob1 = new myclass(1, 'earth'); $ob2 = new myclass(2, 'sky'); $ob3 = new myclass(3, 'ocean');
i want objects $ob1, $ob2 , $ob3 have different attribute $id. example when make :
$ob4 = new myclass(3, 'wood');
the code denies me create object
thanks
you need keep track of ids in static
class property:
class myclass { static private $ids = []; public function __construct($id) { if (in_array($id, self::$ids)) { throw new exception("object id $id constructed"); } self::$ids[] = $id; } }
having said this, question usefulness of this. sounds recipe problems. should keep track of unique data part of business logic , database interaction, not enforced on language level.
Comments
Post a Comment