使用object属性作为method属性的默认值

时间:2008-08-04 17:51:13

标签: php parameters error-handling

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

5 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:6)

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

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

答案 2 :(得分:1)

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

PHP:

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

答案 3 :(得分:1)

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

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

答案 4 :(得分:0)

如果您使用的是PHP 7,则可以改善Kevin的回答:

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