Php 接球手/二传手有什么好处?

Php 接球手/二传手有什么好处?,php,getter-setter,Php,Getter Setter,可能重复: 我一直在想为什么人们在PHP中使用getter/setter而不是使用公共属性 从另一个问题中,我复制了以下代码: <?php class MyClass { private $firstField; private $secondField; public function __get($property) { if (property_exists($this, $property)) { return $this->$proper

可能重复:

我一直在想为什么人们在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中的数据,但是上面的示例并不适合它

getter和setter用于防止类外的代码访问实现细节。也许今天某个数据段只是一个字符串,但明天它将通过将另外两个字符串连接在一起并记录检索字符串的次数来创建。好的,人为的例子

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


另一方面,如果您只想保存数据,那么公共属性就可以了,但我认为这是一种特殊情况。

使用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

如果您将该属性设置为受保护或私有,则无法执行此操作,您可以控制该属性中的内容。

请参阅:@genesis+1。我也从来没用过。这就是构造的目的!哦,主要原因是你可以在设置之前开始验证值,而不必在所有设置属性的情况下更改它?是的,这是另一个很好的原因。在一个地方使用验证代码是一件非常好的事情。嗯,这不适合我的示例代码-实际上每个属性都有一个新的setter。我不。但我明白你的意思mean@genesis对我从不使用神奇的二传手/接球手。magic方法之所以有用的一个原因是,如果您希望将项存储在类中的一个属性中,例如在注册表或服务容器中。上述注释的示例: