【问题标题】:How to set class variables in PHP?如何在 PHP 中设置类变量?
【发布时间】:2016-09-19 09:52:29
【问题描述】:

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

我应该用我的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 提出同样的问题。但我猜你在处理父类的私有变量时必须使用settersgetters

【问题讨论】:

  • 由于您的 getter 和 setter 实际上什么都不做,只是不受限制地获取/设置变量,您不妨将其设为 public 并直接修改它;)
  • 好点。所以你只使用settersgetters 只有当你想做别的事情时,除了原样返回它们吗?
  • @NiettheDarkAbsol - 我不同意。 1) 让一切都成为对象的方法 - 避免混淆 2) 如果要计算其中一个,将来会发生什么?见programmers.stackexchange.com/questions/176876/…

标签: php class private setter


【解决方案1】:

在这样一个微不足道的例子中,是的,您的问题主要是哲学问题! :) 但是,如果您的 setter 会执行一些特殊操作(例如检查输入的有效性或修改输入),那么我建议使用第二种方案。

【讨论】:

  • 这是一个好点 - 所以 setter 是验证输入的好地方?
  • 好点!好吧,“输入”实际上是指函数的参数,而不是用户的输入。一般来说,我更喜欢单独验证用户的输入。但是,对于一些简单的应用程序,您并不总是希望遵循所有最佳实践。一切都取决于您的需求。
【解决方案2】:

这个:

  class foo {

  private $bar;

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

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

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

与此没有什么不同:

类foo{

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

 public $bar;

使用 getter 和 setter 的一个原因是,如果您只允许在对象构造上设置变量,如下所示:

class foo {

  private $bar;

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


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

所以除非必要,否则不要过度使用 getter 和 setter

【讨论】:

    【解决方案3】:

    由于数据验证和未来维护,您应该在构造函数中使用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   ");
    

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

    【讨论】:

      猜你喜欢
      • 2010-09-07
      • 1970-01-01
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多