什么是getters / setter有益?

时间:2012-04-09 15:52:12

标签: php getter-setter

  

可能重复:
  Is it really that wrong not using setters and getters?
  Why use getters and setters?

我一直想知道为什么人们在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;
  }
}
?>

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

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

2 个答案:

答案 0 :(得分:7)

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

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

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

答案 1 :(得分:1)

使用getter和setter可以控制类的属性。看起来像这样的例子:

<?php
class User
{
  public function $name;

  public function __construct($name)
  {
    $this->setName($name);
  }

  public function setName($name )
  {
    if (!preg_match('/^[A-Za-z0-9_\s]+$/')) {
      throw new UnexpectedValueException(sprintf('The name %s is not valid, a name should only contain letters, numbers, spaces and _', $name);
    }
    $this->name = $name;
  }
}
$foo = new User('Foo'); // valid
$foo->name = 'Foo$%^&$#'; // ahh, not valid, but because of the public property why can do this

如果您设置了属性protectedprivate,则无法执行此操作,您可以控制属性中的内容。