新版本的“... or die(...”

发布于 2024-09-14 23:40:30 字数 517 浏览 3 评论 0原文

很久以前,我曾经在我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

稳稳的幸福 2024-09-21 23:40:30

您使用的两个示例没有任何问题,只是您将它们夹在一行上。

我不确定你在寻找什么,或者为什么你会发现 if 语句的错误 - 在这一点上它已经经过了相当多的尝试并且是正确的。也就是说,您可以在 or 运算符中对鞋拔子进行类似的操作,但是在您离开后维护您的代码的人会诅咒您。

function throw_ex($what) {
  throw $what;
}

function fails() {
  return false;
}

$x = fails() or throw_ex(new exception("failed"));

我不明白这比 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.

function throw_ex($what) {
  throw $what;
}

function fails() {
  return false;
}

$x = fails() or throw_ex(new exception("failed"));

I don't see how this gains you anything over the ol' if statement.

乖乖公主 2024-09-21 23:40:30

事实是,您应该使用 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文