Let's say I want to have a set of objects, each of which should have its own unique ID. Nothing fancy is needed, just a letter denoting which type of object it is, and a number denoting how many objects of these have been created. So for instance, a0, a1, b0, c0, c1, c2, c3, and so on.
Rather than setting global variables to keep track of how many of each object already exist, I want to do so with a class. Like so:
class uniqueIDGenerator
{
private $numberAObjs;
private $numberBObjs;
private $numberCObjs;
public function generateID ($type) {
if($type === "A") {
return 'a' . (int) $this->$numberAObjs++;
} else if($type === "B") {
return 'b' . (int) $this->$numberBObjs++;
} else if($type === "C") {
return 'c' . (int) $this->$numberCObjs++;
}
}
}
class obj
{
private $id;
function __construct($type) {
$this->id = uniqueIDGenerator::generateID($type);
}
}
The problem with this is that if uniqueIDGenerator is uninstantiated, its generateID function will always return the same values for each type (e.g. a0, b0, c0, etc.) because its private variables haven't actually been created in memory. At the same time, making it a property of obj won't work because then each time an obj is created, it will have its own instance of uniqueIDGenerator, so that will also always return a0, b0, c0, (assuming it's only called once in that object's methods) and so on.
The only option seems to be to make uniqueIDGenerator its own global instance so obj's constructor can reference it, but that seems poor coding practice. Is there any good, OOP way to do this that keeps all the objects separate and organized?
static- Pierre Emmanuel Lallemant