每个类实例化的唯一随机数

时间:2016-04-15 19:42:44

标签: php class random instance

我希望通过rand()为我班级的每个实例化生成一个随机ID。我希望它是独一无二的。这是我写的,但这不起作用。

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();
        }
    }
}

我故意尝试生成低值,例如rand(1,3),我有三个ID为2,2,1的对象。所以它不起作用。

我认为这是因为类$id_list数组的每个新实例都变为空。但我看到人们几乎做同样的事情。声明$counter变量并将$this->counter++放入__construct方法。那有什么区别?

3 个答案:

答案 0 :(得分:1)

以这种方式使用的$counter变量不是随机的,但它是唯一的。它只是在创建对象时对其进行计数,从0或1开始,具体取决于您的偏好。不同之处在于类的所有对象都在访问同一个变量。要实现这一点,必须将变量声明为静态,如下所示:

public static $counter = 0;

function __construct() 
    self::$counter++;
}

要生成一个也是唯一的随机数,您必须编写一个子程序,将生成的数字与每个实例化对象的id进行比较。这可能会很快变得低效,我不推荐它。但如果你打算这样做,它可能看起来像这样:

class Computer
{
    private $id = 0; // placeholder for ID
    private static $id_list = []; // placeholder to store used IDs

    public function __construct()
    {
        $this->id = self::checkID();
    }

    private static function checkID()
    {
        $newID = rand(1,10000);
        if (!in_array($newID, self::$id_list))
        {
            array_push(self::$id_list, $newID);
            return $newID;
        } else {
            self::checkID();
        }
    }
}

答案 1 :(得分:1)

您需要将$ id_list设为静态,以便保留存储的值,如下所示:

class Computer
{
    private $id = 0; // placeholder for ID
    private static $id_list = []; // placeholder to store used IDs

    public function __construct()
    {
        $this->checkID();
        print_r(self::$id_list);
    }

    private function checkID()
    {
        $this->id = rand(1,3);
        if (!in_array($this->id, self::$id_list))
        {
            array_push(self::$id_list, $this->id);
        } else {
            $this->checkID();
        }
    }
}
for($i = 0; $i < 10; $i++){
    new Computer();
}

我添加了印刷线来展示结果,但你应该明白这一点。

答案 2 :(得分:0)

使用可以使用spl_object_hash()功能:

  

此函数返回对象的唯一标识符。这个id可以   用作存储对象或用于识别对象的哈希键   对象,只要对象不被破坏。一旦对象是   销毁后,其散列可以重用于其他对象。

每次构造对象时都可以调用spl_object_hash()

class Computer
{
    private $id = "";            // placeholder for a unique random Id

    public function __construct()
    {
        $this->id = spl_object_hash( $this );
    }
}

请注意spl_object_hash()返回的值的唯一性有一个“弱”&#39;要点:

  

一旦对象被销毁,其哈希可以重用于其他对象   对象。

在这种情况下,您可以使用以下代码构建自己的hashing机制:

class Computer
{
    private $id = "";            // placeholder for a unique random Id
    private static $seed = 0;    //placeholder for the seed

    public function __construct()
    {
        self::$seed++;
        $this->id = hash('md5', get_class($this) . self::$seed );
    }
 } 

实际上,没有必要检查重复的ID,因为md5哈希在2^128中的冲突概率为1!

相关问题