Stavo eseguendo alcuni test unitari e ho riscontrato un comportamento imprevisto con un'istruzione switch che stavo usando. Ho isolato la condizione qui sotto.Comportamento interruttore PHP imprevisto
function test($val)
{
switch($val)
{
case 'a':
case 'b':
return 'first';
break;
case 'c':
return 'second';
break;
default:
return 'third';
}
}
qui sono il mio primo turno di prove:
test('a') => 'first'
test('b') => 'first'
test('c') => 'second'
test('d') => 'third'
test('0') => 'third'
test('1') => 'third'
test('true') => 'third'
test('false') => 'third'
Questo è abbastanza evidente a destra? ok ora controllare questi fuori:
test(0) => 'first' // expected 'third'
test(1) => 'third'
test(true) => 'first' // expected 'third'
test(false) => 'third'
test(null) => 'third'
test([]) => 'third'
Che cosa è con i risultati strani con 0 e vero? Lo digiterei per perdere digitando se 1/true e 0/false restituivano gli stessi valori. Ma loro no!
Se si converte il valore in a (stringa), lo switch funziona come previsto.
test((string) 0) => 'third'
test((string) 1) => 'third'
test((string) true) => 'third'
test((string) false) => 'third'
Non capisco il motivo per cui l'interruttore wont "lavoro", come ho inteso senza usare "(stringa)"
qualcuno può spiegare perché questo sta accadendo? la documentazione di
Nota che l'interruttore/caso non ha confronto. http://php.net/manual/en/types.comparisons.php#types.comparisions-loose –
E sì, '0' è uguale a' 'a'' in confronto libero, mentre '1' non lo è. https://eval.in/412018 – Jessica
0 == 'a' .... Quindi succede perché PHP. – GolezTrol