2016-11-23 7 views
1

switch文を作成して3つの異なるケースを処理し、結果を返します。 switch文は、falseであるにもかかわらず、常に最初のcaseで起動します。 if/elseステートメントを作成すると、期待通りに機能します。どうしてこれなの? (私は同時にスイッチおよび/他の場合の両方を使用していない、私は私の例を示すために、それらの両方をアンコメントしていことに注意してください)switch文がif/elseと異なる条件を処理する

ここでは、私が働いている機能です。

public static function statuses($statusId = null) 
{ 
    $statuses = [ 
     1 => 'Choose Vendor', 
     2 => 'Approve Quote', 
     3 => 'Waiting on Forecast', 
     4 => 'Waiting on Sign Approval', 
     5 => 'Waiting on Final Approval', 
     6 => 'Waiting on Review', 
     7 => 'Completed' 
    ]; 

    // This works as expected... 
    if (is_numeric($statusId)) { 
     return $statuses[$statusId]; 
    } elseif (is_string($statusId)) { 
     return array_search($statusId, $statuses); 
    } else { 
     return $statuses; 
    } 

    // This does not work as expected 
    switch ($statusId) { 
     case is_numeric($statusId): 
      // This always fires and the result is FALSE 
      var_dump(is_numeric($statusId)); 
      return $statuses[$statusId]; 
     case is_string($statusId): 
      return array_search($statusId, $statuses); 
     default: 
      return $statuses; 
    } 
} 

そして、ここで私は、メソッドの呼び出し午前方法です:私は、引数を渡すわけではないので、配列を返す必要があります

SignVendorJob::statuses() 

+0

[ケースは\ _numeric($ action)は別の方法で記述できますか?](http://stackoverflow.com/questions/8950874/can-case-is-numericaction-be-written-another- –

+3

おそらくそれはif/else文ではないので....効果的なのは 'if($ statusId == is_numeric($ statusId)){...} elseif($ statusId == is_string ($ statusId)){...} else {...} 'これはナンセンスです –

+1

@dericcainそうです、そうでした。後でそれを削除しましたが、P –

答えて

2

Switchステートメントは次のようにする必要があります:

switch (true) { 
    case is_numeric($statusId): 
     // This always fires and the result is FALSE 
     var_dump(is_numeric($statusId)); 
     return $statuses[$statusId]; 
    case is_string($statusId): 
     return array_search($statusId, $statuses); 
    default: 
     return $statuses; 
} 

switch後の変化に注意してください。

あなたの例では、以下の条件を例にテストされています。

$statusId == is_numeric($statusId)$statusId == is_string($statusId) これらは間違った結果が得られます。

+1

基本的には、switch文を正しく使用しない単純なケースです。私は私がテストしているものをスイッチのパラメータに入れて、私がテストしている変数には入れないことにしていることがわかります。それを指摘してくれてありがとう!私はそれができるようになるとすぐにそれをマークします。 – dericcain

+1

@dericcain簡単に言えば:そうです。 – Fracsi

関連する問題