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

Translate

我正在尝试这样做(这会产生意外的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();
    }
}
This question and all comments follow the "Attribution Required."

所有的回答

Translate

这不是更好:

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

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

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

这样您就可以传递0的权重,并且仍然可以正常工作。注意===运算符,它检查权重在值和类型上是否都匹配“ null”(与==相反,后者只是值,所以0 == null == false)。

PHP:

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

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

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

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

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