Getter和Setter? [英] Getter and Setter?
本文介绍了Getter和Setter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不是一个PHP开发人员,所以我想知道在PHP是否更受欢迎使用显式getter / setters,在一个纯OOP风格,与私有字段(我喜欢的方式):
I'm not a PHP developer, so I'm wondering if in PHP is more popular to use explicit getter/setters, in a pure OOP style, with private fields (the way I like):
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;
}
感谢
推荐答案
您可以使用 php魔术方法 __ get
和 __ set
。
<?php
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;
}
return $this;
}
}
?>
这篇关于Getter和Setter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文