gpt4 book ai didi

php - 应避免使用逻辑运算符(使用 || 而不是 'or' ) sensiolabs Insight

转载 作者:行者123 更新时间:2023-12-04 00:39:48 25 4
gpt4 key购买 nike

我使用 SensioLabs Insight 来保持我的项目代码质量高于所用工具的最佳实践。

此行在 SLInsight 分析期间导致警告:

$handle = fopen($file, 'w') or die('Cannot open file: '.$file);

SensioLabs 说:

Logical operators should be avoided.

[...]

The or operator does not have the same precedence as ||. This could lead to unexpected behavior, use || instead.

好的,但是,如果我只是使用 ||而不是 'or' ,如下所示:

$handle = fopen($file, 'w') || die('Cannot open file: '.$file);

由于 fopen 失败,我得到了经典的 No such file or directory 错误,而不是我所期望的(死亡 Action 和返回消息)。

为了避免这种情况,我在执行 fopen 之前使用了一个条件:

if(!file_exists($file)) {
throw $this->createNotFoundException('Le fichier '.$file.' n\'existe pas.');
}
$handle = fopen($file'.log', 'r');

“||”有什么用处在我想要的变量赋值中?

提前感谢您的启发。

最佳答案

Logical operators should be avoided.

在您的情况下,是您想要的 的优先级。我认为 SensioLabs 指的是条件中的复杂表达式,这可能会产生误导。

or 运算符的优先级较低,甚至低于赋值 = 运算符。示例:

if ($a = getRecordOrFalse($userId) || $boolValue) {

正如您所期望的:

if (($a = getRecordOrFalse($userId)) || ($boolValue)) {

$a 包含返回的值 getRecordOrFalse,如果 $boolValue 为 true,则此条件为 true,即使 $a 不是。但是使用 or 你会得到完全不同的行为:

if ($a = getRecordOrFalse($userId) or $boolValue) {

这相当于:

if ($a = (getRecordOrFalse($userId) or $boolValue)) {

现在,$a 将是由 getRecordOrFalse($userId) 或 $boolValue) 条件的结果给出的 bool 值。

但就您而言,这是有道理的:

$handle = (fopen($file, 'w') or die('Cannot open file: '.$file));

为了提高可读性,您可以使用如下条件:

if (false === $handle = fopen($file, 'w')) {
die('Cannot open file: '.$file);
}

或者简单地说

if (!$handle = fopen($file, 'w')) {
die('Cannot open file: '.$file);
}

关于php - 应避免使用逻辑运算符(使用 || 而不是 'or' ) sensiolabs Insight,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33186984/

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