2

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

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 用作用户指定的可读字符串。

提前致谢!

4

3 回答 3

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.');
        }
    }

}

您可以查看此演示

于 2014-02-14T08:01:49.863 回答
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'); 
于 2014-02-14T08:02:02.360 回答
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.');
        }
    }
于 2014-02-14T08:21:41.807 回答