I want to generate a random ID via rand() for every instantiation of my class. And I want it to be unique. Here is what I wrote, but this doesn't work.
class Computer
{
private $id = 0; // placeholder for ID
private $id_list = []; // placeholder to store used IDs
public function __construct()
{
$this->checkID();
}
private function checkID()
{
$this->id = rand(1,3);
if (!in_array($this->id, $this->id_list))
{
array_push($this->id_list, $this->id);
} else {
$this->checkID();
}
}
}
I've tried this intentionally with generating low values, like rand(1,3), and I got three objects with IDs 2, 2, 1. So it's not working.
I assume that is because for every new instance of a class $id_list array becomes empty. But I've seen people doing almost the same thing. Declaring a $counter variable and putting $this->counter++ in the __construct method. So what's the difference?
Aucun commentaire:
Enregistrer un commentaire