我不是 PHP 开发人员,所以我想知道在 PHP 中以纯 OOP 样式和私有字段(我喜欢的方式)使用显式 getter/setter 有哪些优点和缺点:
class MyClass {
private $firstField;
private $secondField;
public function getFirstField() {
return $this->firstField;
}
public function setFirstField($x) {
$this->firstField = $x;
}
public function getSecondField() {
return $this->secondField;
}
public function setSecondField($x) {
$this->secondField = $x;
}
}
或者只是公共领域:
class MyClass {
public $firstField;
public $secondField;
}
原文由 Mark 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用 php 魔术方法
__get
和__set
。