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

Php 使用对象属性作为方法属性的默认值,php,parameters,error-handling,Php,Parameters,Error Handling,我正在尝试这样做(这会产生意外的T_变量错误): 我不想在其中添加一个幻数来表示重量,因为我使用的对象有一个“defaultWeight”参数,如果不指定重量,所有新装运都会得到该参数。我无法将defaultWeight放入装运本身,因为它会随着装运组的不同而变化。有没有比下面更好的方法 public function createShipment($startZip, $endZip, weight = 0){ if($weight <= 0){ $weight

我正在尝试这样做(这会产生意外的T_变量错误):

我不想在其中添加一个幻数来表示重量,因为我使用的对象有一个
“defaultWeight”
参数,如果不指定重量,所有新装运都会得到该参数。我无法将
defaultWeight
放入装运本身,因为它会随着装运组的不同而变化。有没有比下面更好的方法

public function createShipment($startZip, $endZip, weight = 0){
    if($weight <= 0){
        $weight = $this->getDefaultWeight();
    }
}
公共函数createShipping($startZip,$endZip,weight=0){
如果($weight getDefaultWeight();
}
}

这没什么好的:

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,并且仍然可以正常工作。请注意===运算符,它检查权重是否在值和类型中都与“null”匹配(与==相反,后者只是值,因此0==null==false)

PHP:


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

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

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

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

改进Kevin的答案如果您使用的是PHP 7,您可以:

public function createShipment($startZip, $endZip, $weight=null){
    $weight = $weight ?: $this->getDefaultWeight();
}
[@pix0r](#2213)这是一个很好的观点,但是,如果您查看原始代码,如果权重传递为0,它将使用默认权重。
public function createShipment($startZip, $endZip, $weight = 0){
    $weight or $weight = $this->getDefaultWeight();
    ...
}
public function createShipment($startZip, $endZip, $weight=null){
    $weight = $weight ?: $this->getDefaultWeight();
}