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

lnulla 发布于 2018-02-07 parameters 最后更新 2018-02-07 01:05 492 浏览

我试图做到这(产生一个意想不到的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();
    }
}
已邀请:

inemo

赞同来自:

这不是好多了:

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

baut

赞同来自:

这将允许您传递0的权重,并仍然正常工作。注意===运算符,它检查是否在weight和type中匹配“null”(相对于==,它只是value,所以0 == null == false)。 PHP:

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

mex

赞同来自:

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

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

beos

赞同来自:

布尔或运算符巧妙的技巧:

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