使用PHP的三元运算符来检查数据库中的INSERT是否成功(或者更一般地说,检查任何函数的返回值),这是可以接受的做法吗?PHP手册似乎对堆叠的三元运算符持谨慎态度,我在writeData
函数中嵌入了一些。
#pseudocode variables to give context
$conn = new PDO("mysql:host=localhost;dbname=blah", $user, $pass);
$form = sanitize($_POST);
#writeData returns true on success, false if PDO exception
#do nothing on success, warn if otherwise
writeData($conn, $form) ? : exit("Problem writing data to database.");
编辑:
我实际上try
&CCD_ 4函数中的CCD_。我还没有输出错误页面。假设我写了错误页面代码,然后在writeData
的catch
块中输出,最好这样做吗:
if(!writeData($conn, $form)) die();
(或者三元版本,我有点同意它很难阅读,尤其是在这种情况下)
在这种特殊情况下,不,这是不可接受的。or die
是2000年处理错误的方法,从2015年起,你应该使用异常(这就是它们的用途):
try {
writeData($conn, $form);
} catch(PDOException $e) {
// try to recover, if possible
// log the error
// give the user a nicely formatted error page
}
在我看来,使用三元运算符从来都不是一种好的做法。适当的条件句总是更容易阅读和理解。争论还在继续。