我在 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)变量时必须使用 setters
和 getters
。
最佳答案
由于数据验证和将来的维护,您应该在构造函数中使用 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/