什么是getters/setter有益?

gen*_*sis -4 php getter-setter

可能重复:
不使用setter和getter真是错吗?
为什么要使用getter和setter?

我一直想知道为什么人们在PHP中使用getter/setter而不是使用公共属性?

从另一个问题,我复制了这段代码:

<?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;
  }
}
?>
Run Code Online (Sandbox Code Playgroud)

我认为这与使用公共字段没有区别.

好吧,我知道它可以帮助我们验证getter和setter中的数据,但上面的例子并不适合它

Ror*_*ter 7

使用getter和setter是为了防止类中的代码访问实现细节.也许今天某些数据只是一个字符串,但明天它是通过将两个其他字符串连接在一起创建的,并且还保留了字符串检索次数的计数(好的,人为的例子).

关键是通过强制访问您的类来访问方法,您可以自由地更改类的工作方式,而不会影响其他代码.公共财产不会给您这种保证.

另一方面,如果你想做的就是保存数据,那么公共属性就可以了,但我认为这是一个特例.