2013-12-15 26 views

回答

1
function temperature_unit($type) { 
    if (!in_array($type, array('C', 'F'), true)) 
    throw new InvalidArgumentException('$type must be C or F'); 
    // rest of your function 
} 

如果您愿意,您可以拨打trigger_error来代替例外情况。

你也可以使用switch语句,并抛出异常在默认情况下:

function temperature_unit($type) { 
    switch ($type) { 
    case 'F': 
     // do work in F 
     break; 
    case 'C': 
     // do work in C 
     break; 
    default: 
     throw new InvalidArgumentException('$type must be C or F'); 
    } 
} 
+0

感谢这个工作! –

+0

现在我还有一个问题,我可以做些什么来检查'$ type'是'F'还是'C'? –

+0

@ Me123:如果你只检查它是否等于一个值,只需使用一个相等运算符:'if($ type ==='F')',或者查看我更新后的答案。 –

相关问题