[英]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.