我不喜欢拥有数百个幼稚的 Setter 和 Getter,但我希望能够为某些数据使用 Setter 和 Getter,因为我可能需要对它们进行清理等。
我有两个想法如何做到这一点:
class Test {
private $value = "Value received from: ";
private $value2 = "Value2 received from: ";
function __get($property) {
if (method_exists($this, "get".$property)) {
return $this->getValue();
}
return $this->$property."__get()";
}
public function getValue() {
return $this->value."getValue()";
}
}
$obj = new Test();
echo $obj->value; // Returns: Value received from: getValue()
echo $obj->value2; // Returns: Value2 received from: __get()
和
class Test {
private $value = "Value received from: ";
private $value2 = "Value2 received from: ";
public function __call($method, $args) {
if (substr($method, 0, 3) == "get") {
// Sanitizing so no functions should get through
$property = preg_replace("/[^0-9a-zA-Z]/", "", strtolower(substr($method, 3)));
if (isset($this->$property)) {
return $this->$property."__call";
}
}
}
public function getValue() {
return $this->value."getValue()";
}
}
$obj = new Test();
echo $obj->getValue(); // Returns: Value received from: getValue()
echo $obj->getValue2(); // Returns: Value2 received from: __call
基本上唯一的区别是魔术方法__call
和__get
. 我漏掉了,__set
因为很明显我会怎么做。
真正的问题是哪个更好?表现?可读性?安全?