我的问题很简单,但我似乎无法在网上找到任何答案。我可能会直接跳到代码中:
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作为可读字符串,由用户指定。
提前致谢!
答案 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.');
}
}