[英]How to set class variables in PHP?
我在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
也可以问同样的问题。 但是我想您在处理父类的私有变量时必须使用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 ");
开发人员认为自己已修复该错误,因此将该代码发送到生产环境。
在这样一个简单的例子中,是的,您的问题主要是哲学上的! :)但是,如果您的设置者将执行某些特殊操作(例如检查输入的有效性或对其进行修改),那么我建议使用第二种方案。
这个:
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方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.