PHP OOP:所有类实例中的唯一ID属性

时间:2014-02-14 07:56:06

标签: php oop properties unique-id

我的问题很简单,但我似乎无法在网上找到任何答案。我可能会直接跳到代码中:

class NewClas {
    public $id;

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

        $this->checkVars();
    }

    public function checkVars() {
        if (empty($this->id)) {
            trigger_error('ID is a required parameter.');
        } elseif ($this->id WAS USED IN A PREVIOUS OBJECT) {
            trigger_error('ID "'.$this->id.'" was used already. Please insert a unique name.');
        }
    }

}

$object1 = new NewClass('id1');
$object2 = new NewClass('id2');
$object3 = new NewClass('id1'); // throws error, because id1 was already used

那么 - 是否有可能在类的所有实例中检查属性值的唯一性?我刚刚开始使用OOP,所以请放轻松我。 :)

另外,我知道spl_object_hash但我更喜欢使用ID作为可读字符串,由用户指定。

提前致谢!

3 个答案:

答案 0 :(得分:2)

有可能 - 如果你将存储使用过的id的静态注册表。那是关于:

class NewClass
{
    public $id;
    //here's your registry
    protected static $registry = array();

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

        $this->checkVars();
        //if not failed, add to registry:
        self::$registry[] = $id;
    }

    public function checkVars() 
    {
        if (empty($this->id)) 
        {
            trigger_error('ID is a required parameter.');
        }
        //checking if it's already used: 
        elseif (in_array($this->id, self::$registry)) 
        {
            trigger_error('ID "'.$this->id.'" was used already. Please insert a unique name.');
        }
    }

}

您可以查看demo

答案 1 :(得分:1)

它不会抛出任何错误。您正在使用trigger_error块下的else触发错误。这就是你收到错误的原因。

当你这样做时..

$object3 = new NewClass('id1');

id1作为参数传递给构造函数,并设置为$id公共变量。现在checkVars()将被调用..此处$this->id不会为空,因此它将转到else块。

实际上这是正确的代码..

<?php

class NewClass {
    public $id;

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

        $this->checkVars();
    }

    public function checkVars() {
        if (empty($this->id)) {
            trigger_error('ID is a required parameter.');
        } else {
           // trigger_error('ID is already used.');
        }
    }

}

$object1 = new NewClass('id1');
$object2 = new NewClass('id2');
$object3 = new NewClass('id1'); 

答案 2 :(得分:0)

这是以上答案的正确答案: 但是为了尊重SOLID OOP设计原则,我建议将id设为私有,并使用getter和setter来访问它。

class NewClass
{
    private $id;
    //here's your registry
    public static $registry = array(); //since is static you can make it public

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

        $this->checkVars();
        //if not failed, add to registry:
        self::$registry[] = $id;
    }

    public function checkVars() 
    {
        if (empty($this->id)) 
        {
            trigger_error('ID is a required parameter.');
        }
        //checking if it's already used: 
        else if (in_array($this->id, self::$registry)) 
        {
            trigger_error('ID "'.$this->id.'" was used already. Please insert a unique name.');
        }
    }