可能重复:
魔术方法是 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) 使用传统的 setter 和 getter
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 来做它不想做的事情。它奏效了。却让坏事发生。
但我想听听更多关于这方面的意见。