使用对象属性作为方法属性的默认值

我试图做到这一点(这会产生意想不到的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();
    }
}
0
额外 编辑
意见: 1

4 答案

这并不好多了:

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();
}
0
额外

这将允许您传递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,

布尔OR运算符的巧妙操作:

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

您可以使用静态类成员来保存默认值:

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