gpt4 book ai didi

php - 在 PHP 中替代 'or' 关键字

转载 作者:可可西里 更新时间:2023-11-01 13:35:54 24 4
gpt4 key购买 nike

现在我有以下代码:

stream_wrapper_register("var", "VariableStream")
or die("Failed to register protocol");

而且我想在死之前做一些额外的事情以防函数失败。所以它提出了这个问题:

“or”关键字究竟是如何工作的?

在许多 SO 问题或答案中,我看到人们创建了一个函数,如下所示:

function doStuff() {
header('HTTP/1.1 500 Internal Server Error');
die("Failed to register protocol");
}

stream_wrapper_register("var", "VariableStream")
or doStuff();

...但这在面向对象的上下文中有点不切实际,因为我真的不想在我的对象中为此创建一个方法,而且我还不能使用闭包。

所以现在,我已经使用了这段代码,但我不确定它是否具有完全相同的行为:

if (!stream_wrapper_register("var", "VariableStream") {
header('HTTP/1.1 500 Internal Server Error');
die("Failed to register protocol");
}

最佳答案

带有“or”的语句有效,因为 PHP-Interpreter 非常智能:因为“或”的连接为真,所以如果第一个为真,则在第一个为真时停止执行语句。

想象以下 (PHP) 代码:

function _true()  { echo "_true";  return true;  }
function _false() { echo "_false"; return false; }

现在您可以链接函数调用并在输出中查看发生了什么:

_true() or _true() or _true();

只会告诉你“_true”,因为链在第一个为真后结束,其他两个永远不会被执行。

_false() or _true() or _true();

将给出“_false_true”,因为第一个函数返回 false 并且解释器继续。

同样适用于“and”

你也可以对“and”做同样的事情,不同的是,当第一个“false”出现时,“and”的链就结束了:

_false() and _true() and _true();

将回显“_false”,因为结果已经完成,无法再更改。

_true() and _true() and _false();

会写“_true_true_false”。

因为大多数函数都通过在成功时返回“1”和在错误时返回 0 来指示它们的成功,因此您可以执行 function() 或 die() 之类的操作。但是有些函数(在 php 中很少)在成功时返回“0”,并且 != 0 表示特定错误。那么你可能不得不使用 function() 和 die()

关于php - 在 PHP 中替代 'or' 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9114238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com