如何在PHP中设置class变量?
How to set class variables in PHP?
我在 php 中有一个 class 并且想知道是否有关于如何在我的构造函数中设置这些私有变量的特定约定。
我应该用 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
也可以问同样的问题。但我猜你在处理 parent class.
的私有变量时必须使用 setters
和 getters
在这样一个微不足道的例子中,是的,你的问题主要是哲学问题! :)
但是,如果您的 setter 会执行一些特殊操作(例如检查输入的有效性或修改它),那么我建议使用第二种方案。
这个:
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{
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;
}
}
所以除非必要,否则不要过度使用 getters 和 setters
您应该在构造函数中使用 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 中有一个 class 并且想知道是否有关于如何在我的构造函数中设置这些私有变量的特定约定。
我应该用 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
也可以问同样的问题。但我猜你在处理 parent class.
setters
和 getters
在这样一个微不足道的例子中,是的,你的问题主要是哲学问题! :) 但是,如果您的 setter 会执行一些特殊操作(例如检查输入的有效性或修改它),那么我建议使用第二种方案。
这个:
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{
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;
}
}
所以除非必要,否则不要过度使用 getters 和 setters
您应该在构造函数中使用 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 ");
开发人员将代码发送到生产认为他修复了错误。