PHP:'或'语句失败:如何抛出新的异常?

Str*_*rae 19 php exception-handling exception logical-operators

这里的每个人都应该知道'或'状态,通常粘在die()命令上:

$foo = bar() or die('Error: bar function return false.');
Run Code Online (Sandbox Code Playgroud)

大多数时候我们看到类似的东西:

mysql_query('SELECT ...') or die('Error in during the query');
Run Code Online (Sandbox Code Playgroud)

但是,我无法理解'或'语句究竟是如何工作的.

我想抛出一个新的异常而不是die(),但是:

try{
    $foo = bar() or throw new Exception('We have a problem here');
Run Code Online (Sandbox Code Playgroud)

不起作用,也不起作用

$foo = bar() or function(){ throw new Exception('We have a problem here'); }
Run Code Online (Sandbox Code Playgroud)

我发现这样做的唯一方法是这个可怕的想法:

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();
}
Run Code Online (Sandbox Code Playgroud)

但是有一种方法可以在'或'语句之后直接抛出新的异常吗?

或者这种结构是强制性的(我完全不依赖于ThrowMe功能):

try{
    $foo = bar();
    if(!$foo){
        throw new Exception('We have a problem in here');
    }
}catch(Exception $e){
    echo $e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)

编辑:我想要的是真的避免使用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.
Run Code Online (Sandbox Code Playgroud)

Pet*_*ley 32

or只是一个逻辑运算符,它类似于||.

常见的伎俩

mysql_query() or die();
Run Code Online (Sandbox Code Playgroud)

也可以写

mysql_query() || die();
Run Code Online (Sandbox Code Playgroud)

这里发生的是"逻辑或"运算符(无论你选择哪个)试图确定任一操作数是否为TRUE.这意味着操作数必须是可以作为布尔值转换的表达式.

所以,原因

bar() or throw new Exception();
Run Code Online (Sandbox Code Playgroud)

是非法的,是因为

(boolean)throw new Exception();
Run Code Online (Sandbox Code Playgroud)

也是非法的.实质上,抛出异常的过程不会生成操作员检查的返回值.

但是调用一个函数产生一个返回值,供操作员检查(没有显式的返回值会导致返回的函数返回到NULL哪个FALSE),这就是当你在函数中包装异常时它适用于你的原因.

希望有所帮助.

  • `或'与`||`不相似.前者的优先级低于赋值和比较.后者有更高.这是一个非常重要的区别因为`$ f = one()或two()`与`$ f = one()||的工作方式非常不同 两()`.http://us3.php.net/manual/en/language.operators.precedence.php (3认同)
  • 是的。“类似”并不意味着“相同”。话虽如此,欢迎您的澄清:D (2认同)