オブジェクトプロパティをメソッドプロパティのデフォルトとして使用する

StackOverflow https://stackoverflow.com/questions/1453

  •  08-06-2019
  •  | 
  •  

質問

私はこれをやろうとしています(予期しない 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();
    }
}
役に立ちましたか?

解決

これはそれほど良いことではありません:

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

他のヒント

ブール OR 演算子を使った巧妙なトリック:

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

これにより、重み 0 を渡しても適切に動作するようになります。=== 演算子に注目してください。これは、重みが値と型の両方で「null」に一致するかどうかを確認します (== とは対照的に、値だけであるため、0 == null == false)。

PHP:

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

静的クラス メンバーを使用してデフォルトを保持できます。

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

PHP 7 を使用している場合は、Kevin の回答を改善して、次のようにすることができます。

public function createShipment($startZip, $endZip, $weight=null){
    $weight = $weight ?: $this->getDefaultWeight();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top