简体   繁体   English

如何在PHP中设置类变量?

[英]How to set class variables in PHP?

I have a class in php and want to know if there is a specific convention how to set these private variables in my constructor. 我在php中有一个类,想知道是否有特定的约定如何在我的构造函数中设置这些私有变量。

Should I set them with my setter or with this ? 我应该用我的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;
  }
}

OR 要么

class foo {

  private $bar;

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

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

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

Or is my question just philosophical? 还是我的问题只是哲学上的? Same question could be asked with getters . getters也可以问同样的问题。 But I guess you have to use setters and getters when handling private variables of your parent class. 但是我想您在处理父类的私有变量时必须使用settersgetters

You should use the setBar in the constructor because of data validation, and future maintenance. 由于数据验证和将来的维护,应在构造函数中使用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   ");

The developer sends the code to production thinking he fixed the bug. 开发人员认为自己已修复该错误,因此将该代码发送到生产环境。

In such a trivial example, yes your question is mostly philosophical! 在这样一个简单的例子中,是的,您的问题主要是哲学上的! :) However, if your setter would perform some special actions (such like checking the validity of the input, or modifiying it), then I would recommend to use the second scheme. :)但是,如果您的设置者将执行某些特殊操作(例如检查输入的有效性或对其进行修改),那么我建议使用第二种方案。

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;
  }
}

is no different than this: 没什么不同:

class foo{ foo类{

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

 public $bar;

One reason to use a getter and a setter is if you only allow a variable to be set on object construction like the following: 使用getter和setter的一个原因是,如果仅允许在对象构造上设置变量,如下所示:

class foo {

  private $bar;

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


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

So don't overuse getters and setters unless necessary 因此,除非必要,请勿过度使用getter和setter方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM