2008-08-04 105 views
21

我試圖做到這一點(這會產生意想不到的T_VARIABLE錯誤):使用對象屬性爲默認方法財產

public function createShipment($startZip, $endZip, $weight = $this->getDefaultWeight()){} 

我不希望把一個神奇的數字在那裏爲重,因爲我使用的對象具有"defaultWeight"參數,如果您未指定重量,則所有新貨件都會得到。我不能將defaultWeight放入貨件本身,因爲它從發貨組更改爲貨件組。有沒有比以下更好的方法來做到這一點?

public function createShipment($startZip, $endZip, weight = 0){ 
    if($weight <= 0){ 
     $weight = $this->getDefaultWeight(); 
    } 
} 

回答

13

這不是更好:

public function createShipment($startZip, $endZip, $weight=null){ 
    $weight = !$weight ? $this->getDefaultWeight() : $weight; 
} 

// or... 

public function createShipment($startZip, $endZip, $weight=null){ 
    if (!$weight) 
     $weight = $this->getDefaultWeight(); 
} 
1

這將允許你通過的0重量並仍能正常工作。注意===運算符,它檢查是否在weight和type中匹配「null」(相對於==,它只是value,所以0 == null == false)。

PHP:

public function createShipment($startZip, $endZip, $weight=null){ 
    if ($weight === null) 
     $weight = $this->getDefaultWeight(); 
} 
+0

[@ pix0r]( #2213)這是一個很好的觀點,但是,如果您查看原始代碼,如果權重傳遞爲0,則它​​使用默認權重。 – Kevin 2008-08-06 22:58:35

1

您可以使用一個靜態類部件保持默認:

class Shipment 
{ 
    public static $DefaultWeight = '0'; 
    public function createShipment($startZip,$endZip,$weight=Shipment::DefaultWeight) { 
     // your function 
    } 
} 
6

絕招用OR運算符:

public function createShipment($startZip, $endZip, $weight = 0){ 
    $weight or $weight = $this->getDefaultWeight(); 
    ... 
}