Is it worth doing this way?
It depends.
Abstracting a field from the user by exposing a "smart" property (i.e. getter and/or setter) has two disadvantages:
- You need to write more code; if the property doesn't really do anything smart, this is code that does nothing useful.
- The user of the property is slightly inconvenienced because they have to type a little more as well.
And it has one advantage:
- In the future you can add logic to the properties even if there was none before without breaking your users' code.
If this advantage is meaningful (e.g. you are writing a reusable software library) then it makes great sense to write properties instead of bare fields. If not, you are doing work for no benefit.
What is the best way to handle such thing?
You can override the magic __get
and __set
functions (perhaps in a base class so you can inherit the override as well) to automatically forward property accesses to your getters and setters. Simplified code:
public function __get($name) {
$getter = 'get'.$name;
if (method_exists($this, $getter)) {
return $this->$getter();
}
$message = sprintf('Class "%1$s" does not have a property named "%2$s" or a method named "%3$s".', get_class($this), $name, $getter);
throw new OutOfRangeException($message);
}
public function __set($name, $value) {
$setter = 'set'.$name;
if (method_exists($this, $setter)) {
return $this->$setter($value);
}
$getter = 'get'.$name;
if (method_exists($this, $getter)) {
$message = sprintf('Implicit property "%2$s" of class "%1$s" cannot be set because it is read-only.', get_class($this), $name);
}
else {
$message = sprintf('Class "%1$s" does not have a property named "%2$s" or a method named "%3$s".', get_class($this), $name, $setter);
}
throw new OutOfRangeException($message);
}
Caveat emptor: Since __get
and __set
are overridden, __isset
and __unset
should be overridden as well!
Is there any security concerned doing it in this way?
No, none at all (assuming you don't insert bugs accidentally).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…