My question is simple, but I can't seem to find any answer for it online. I will probably jump straight into the code:
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
So - is it possible to check for uniqueness of a value of the property among all instances of the class? I am just getting started with OOP, so please go easy on me. :)
Also, I am aware of spl_object_hash
but I would prefer work with IDs as readable strings, specified by a user.
Thanks in advance!
It is possible - if you'll store static registry of used id's. That's about:
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.');
}
}
}
You can check this demo
It won't throw any error. You are triggering the error using the trigger_error
under the else
block. That's the reason you are getting an error.
When you do this..
$object3 = new NewClass('id1');
The id1
is passed as the parameter to the constructor and it is set to the $id
public variable. Now checkVars()
is going to be called .. Here $this->id
will not be empty, so it will go to the else
block.
<?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');
This is the right answer from above answer: But to respect SOLID OOP design principles I would recommend to make id private and use getters and setters to access it.
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.');
}
}