可能是重复问题:
在PHP中,魔术方法是最佳实践吗?
这些只是简单的示例,但想象一下你的类中有超过两个属性。
最佳实践应该是什么?
a) 使用 __get 和 __set。
class MyClass {
private $firstField;
private $secondField;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
}
}
$myClass = new MyClass();
$myClass->firstField = "This is a foo line";
$myClass->secondField = "This is a bar line";
echo $myClass->firstField;
echo $myClass->secondField;
/* Output:
This is a foo line
This is a bar line
*/
b) 使用传统的设置器和获取器
class MyClass {
private $firstField;
private $secondField;
public function getFirstField() {
return $this->firstField;
}
public function setFirstField($firstField) {
$this->firstField = $firstField;
}
public function getSecondField() {
return $this->secondField;
}
public function setSecondField($secondField) {
$this->secondField = $secondField;
}
}
$myClass = new MyClass();
$myClass->setFirstField("This is a foo line");
$myClass->setSecondField("This is a bar line");
echo $myClass->getFirstField();
echo $myClass->getSecondField();
/* Output:
This is a foo line
This is a bar line
*/
在这篇文章中:http://blog.webspecies.co.uk/2011-05-23/the-new-era-of-php-frameworks.html
作者声称使用魔术方法不是一个好主意:
首先,当时非常流行使用PHP的魔术函数(__get,__call等)。从表面上看,它们没有什么问题,但实际上它们非常危险。它们使API变得不清晰,自动完成不可能,最重要的是它们很慢。使用它们的用例是通过黑客手段让PHP执行它本来不想做的事情。虽然这样做确实有效,但会引发一些不好的后果。
但我想听听更多人的意见。