这里的每个人都应该知道“或”语句,通常粘在 die() 命令上:
$foo = bar() or die('Error: bar function return false.');
大多数时候我们会看到类似的东西:
mysql_query('SELECT ...') or die('Error in during the query');
但是,我无法理解那个“或”语句的工作原理。
我想抛出一个新异常而不是 die(),但是:
try{
$foo = bar() or throw new Exception('We have a problem here');
不起作用,也没有
$foo = bar() or function(){ throw new Exception('We have a problem here'); }
我发现这样做的唯一方法是这个可怕的想法:
function ThrowMe($mess, $code){
throw new Exception($mess, $code);
}
try{
$foo = bar() or ThrowMe('We have a problem in here', 666);
}catch(Exception $e){
echo $e->getMessage();
}
但是有一种方法可以在 'or' 语句之后直接抛出一个新异常?
或者这种结构是强制性的(我根本不喜欢 ThrowMe 函数):
try{
$foo = bar();
if(!$foo){
throw new Exception('We have a problem in here');
}
}catch(Exception $e){
echo $e->getMessage();
}
编辑:我真正想要的是避免使用 if() 检查我所做的每一个潜在的危险操作,例如:
#The echo $e->getMessage(); is just an example, in real life this have no sense!
try{
$foo = bar();
if(!$foo){
throw new Exception('Problems with bar()');
}
$aa = bb($foo);
if(!$aa){
throw new Exception('Problems with bb()');
}
//...and so on!
}catch(Exception $e){
echo $e->getMessage();
}
#But i relly prefer to use something like:
try{
$foo = bar() or throw new Exception('Problems with bar()');
$aa = bb($foo) or throw new Exception('Problems with bb()');
//...and so on!
}catch(Exception $e){
echo $e->getMessage();
}
#Actually, the only way i figured out is:
try{
$foo = bar() or throw new ThrowMe('Problems with bar()', 1);
$aa = bb($foo) or throw new ThrowMe('Problems with bb()', 2);
//...and so on!
}catch(Exception $e){
echo $e->getMessage();
}
#But i'll love to thro the exception directly instead of trick it with ThrowMe function.