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

cmc*_*loh 26 php parameters error-handling

我正在尝试这样做(产生意外的T_VARIABLE错误):

public function createShipment($startZip, $endZip, $weight = 
$this->getDefaultWeight()){}
Run Code Online (Sandbox Code Playgroud)

我不想在那里放一个神奇的数字来表示重量,因为我使用的对象有一个"defaultWeight"参数,如果你没有指定重量,所有新货都会得到.我无法将defaultWeight货物装入货物本身,因为它从装运组变为装运组.有没有比以下更好的方法呢?

public function createShipment($startZip, $endZip, weight = 0){
    if($weight <= 0){
        $weight = $this->getDefaultWeight();
    }
}
Run Code Online (Sandbox Code Playgroud)

Kev*_*vin 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();
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*cki 6

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

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