新版本的“... or die(...”
很久以前,我曾经在我的 PHP 代码中使用“or die”。尤其是这样的:
$q = mysql_query('......') or die(mysql_error());
显然,现在这非常可耻,但 X 或 Y 原则仍然对我有用。 所以我想尝试一下:
$r = $this->exec($query) or throw new Exception('FAIL');
但这会导致解析错误! 此类声明的最佳实践是什么?它也必须看起来不错(显然!)...
我不喜欢
if ( !($r = $this->exec($query)) ) throw new ...
或
$r = $this->exec($query)
if ( !$r ) throw new ....
有什么最喜欢的吗?沮丧?最佳实践?速度总是好的。
A long time ago I used to use "or die" in my PHP code. Especially like this:
$q = mysql_query('......') or die(mysql_error());
Obviously, that's pretty shameful these days, but the X or Y principle still speaks to me.
So I though I'd try this:
$r = $this->exec($query) or throw new Exception('FAIL');
but that results in a parse error!
What's the best practice for such statements. It has to look nice as well (obviously!)...
I don't like
if ( !($r = $this->exec($query)) ) throw new ...
or
$r = $this->exec($query)
if ( !$r ) throw new ....
Any favourites? Discouragements? Best practices? Speed is always nice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您使用的两个示例没有任何问题,只是您将它们夹在一行上。
我不确定你在寻找什么,或者为什么你会发现 if 语句的错误 - 在这一点上它已经经过了相当多的尝试并且是正确的。也就是说,您可以在
or
运算符中对鞋拔子进行类似的操作,但是在您离开后维护您的代码的人会诅咒您。我不明白这比 ol' if 语句有什么好处。
There's nothing wrong with the two examples you used, except that you've sandwitched them onto one line.
I'm not sure what you're looking for, or why you're finding fault with an if statement - it's pretty tried and true at this point. That said, you can do something like this to shoe-horn in the
or
operator, but whoever maintains your code after you're gone will curse you.I don't see how this gains you anything over the ol' if statement.
事实是,您应该使用 if 语句来捕获实际的、可恢复的错误。特别是如果您使用 InnoDB,它在正常操作期间有时会出现死锁,处理它们的正确方法不是 die(),而只是再次提交查询。
更多信息请参见:http://arjen-lentz.livejournal.com/150464.html
Fact of the matter is, you should be using if statements to catch actual, recoverable errors. Especially if you are using InnoDB which can sometimes have deadlocks during normal operation and the proper way to handle them isn't to die(), but simply submit the query again.
More info here: http://arjen-lentz.livejournal.com/150464.html