28

我正在尝试这样做(这会产生意外的 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();
    }
}
4

5 回答 5

15

这也好不到哪里去:

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();
}
于 2008-08-04T17:53:00.410 回答
6

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

public function createShipment($startZip, $endZip, $weight = 0){
    $weight or $weight = $this->getDefaultWeight();
    ...
}
于 2008-08-28T08:10:48.643 回答
1

这将允许您传递 0 的权重并且仍然可以正常工作。请注意 === 运算符,它检查权重是否在值和类型中都匹配“null”(与 == 相反,它只是值,因此 0 == null == false)。

PHP:

public function createShipment($startZip, $endZip, $weight=null){
    if ($weight === null)
        $weight = $this->getDefaultWeight();
}
于 2008-08-05T12:49:44.517 回答
1

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

class Shipment
{
    public static $DefaultWeight = '0';
    public function createShipment($startZip,$endZip,$weight=Shipment::DefaultWeight) {
        // your function
    }
}
于 2008-08-28T01:56:13.800 回答
0

如果您使用的是 PHP 7,请改进 Kevin 的回答,您可以这样做:

public function createShipment($startZip, $endZip, $weight=null){
    $weight = $weight ?: $this->getDefaultWeight();
}
于 2019-06-04T09:34:14.470 回答