php - 如何在 PHP 中设置类变量?

标签 php class private setter

我在 php 中有一个类,想知道是否有特定的约定如何在我的构造函数中设置这些私有(private)变量。

我应该使用我的 setter 还是使用 this 设置它们?

class foo {

  private $bar;

  public function __construct($foobar) {
     $this->bar = $foobar;
  }

  public function setBar($bar) {
    $this->bar = $bar;
  }

  public function getBar() {
    return $this->bar;
  }
}

class foo {

  private $bar;

  public function __construct($foobar) {
     $this->setBar($foobar);
  }

  public function setBar($bar) {
    $this->bar = $bar;
  }

  public function getBar() {
    return $this->bar;
  }
}

或者我的问题只是哲学问题? 同样的问题也可以用 getters 来问。但我猜你在处理父类的私有(private)变量时必须使用 settersgetters

最佳答案

由于数据验证和将来的维护,您应该在构造函数中使用 setBar

// a developer introduces a bug because the string has padding.
$foo->setBar("chickens   ");

// the developer fixes the bug by updating the setBar setter
public function setBar($bar) {
    $this->bar = trim($bar);
}

// the developer doesn't see this far away code
$f = new foo("chickens   ");

开发人员将代码发送到生产环境,认为他修复了错误。

关于php - 如何在 PHP 中设置类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37375361/

相关文章:

php - WordPress PSR-4 命名空间插件访问另一个命名空间插件

php - 无法在命令行中访问 PHP 命令

php - 静态 HTML 还是 PHP 生成的 HTML?

PHP - 类忘记设置变量

Typescript - 重载私有(private)方法

PHP 使用私有(private)方法作为回调

javascript - jquery 倒计时今天日期

php - 将正则表达式与Elastica一起使用

Java : Why sometimes we get new object from method instead creating from constructor?

java - 如何从 Java 中的不同类读取私有(private)字段的值?