这里的每个人都应该知道“或”语句,通常粘在 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.
最佳答案
or
只是一个 logical operator ,它类似于 ||
。
常用技巧
mysql_query() or die();
也可以这样写
mysql_query() || die();
此处发生的是“逻辑或”运算符(无论您选择哪个)试图确定任一操作数的计算结果是否为 TRUE。这意味着操作数必须是可以转换为 bool 值的表达式。
所以,原因
bar() or throw new Exception();
是非法的,是因为
(boolean)throw new Exception();
也是非法的。本质上,抛出异常的过程不会产生返回值供操作者检查。
但是调用一个函数确实生成一个返回值供运算符检查(没有明确的返回值将导致函数返回NULL
,它被转换为FALSE
) 这就是为什么当您在函数中包装异常抛出时它对您有用。
关于PHP: 'or' 指令失败语句:如何抛出新异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1211237/