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

===============>>#1 票数: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();
}

===============>>#2 票数:6

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

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

===============>>#3 票数:1

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

PHP:

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

===============>>#4 票数:1

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

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

===============>>#5 票数:0

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

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

  ask by cmcculloh translate from so

未解决问题?本站智能推荐: