2016-05-22 89 views
2

我有一個類在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; 
    } 
} 

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

或者是我的問題只是哲學? 同樣的問題可以用getters詢問。但我想你在處理父類的私有變量時必須使用settersgetters

+2

由於你的getter和setter字面上沒有任何限制,所以不需要設置變量,你可以將它設置爲public並直接修改; –

+0

好點。所以,只有當你想在別的地方做點別的事情時才使用'setters'和'getters',然後按原樣返回它們呢? – Jurik

+1

@NiettheDarkAbsol - 我不同意。 1)把所有東西都作爲對象的一種方法 - 避免混淆2)如果要計算其中的一個,將來會發生什麼?請參閱http://programmers.stackexchange.com/questions/176876/why-shouldnt-i-be-using-public-variables-in-my-java-class –

回答

2

由於數據驗證和將來的維護,您應該在構造函數中使用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 "); 

開發人員將代碼發送給生產思考他修正了錯誤。

1

在這樣一個微不足道的例子中,是的,你的問題大多是哲學的! :) 但是,如果你的setter會執行一些特殊的操作(例如檢查輸入的有效性或修改它),那麼我會建議使用第二種方案。

+0

這是一個好點 - 所以二傳手是一個很好的地方驗證輸入? – Jurik

+1

好點!那麼,通過「輸入」,我的意思是功能的論點,而不是用戶的輸入。一般來說,我更喜歡單獨驗證用戶的輸入。但是,通過一些簡單的應用程序,您並不總是希望遵循所有最佳實踐。一切都取決於你的需求。 – Abrab

1

此:

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,除非必要