php - 使用 @ 获取可能不存在的数组元素的 int 值可能存在哪些陷阱?

标签 php error-handling

我正在尝试获取 $array[$key] 的整数值。 如果未设置 $array[$key],结果应为 0。 作为快捷方式,我使用这个:

@(int)$array[$key]

我听说使用“@”不是最佳做法,所以我想知道使用此快捷方式可能有哪些缺点?

最佳答案

就您而言,最大的缺点是非常不清楚您想要实现什么目标。如果我读到这样的代码,我不会知道你想将未设置的值变成 0 ...

如果您绝对想在一行中包含某些内容,但又保留一些逻辑,那么三元运算符就可以。

$val = (isset($array[$key])) ? (int) $array[$key] : 0;

另外,@ 也有一些表演,看看点赞最多的评论之一(第三个 atm):

http://php.net/manual/en/language.operators.errorcontrol.php

"If you're wondering what the performance impact of using the @ operator is [...] the second script (using the @ operator) takes 1.75x as long to execute... almost double the time of the first script."

关于php - 使用 @ 获取可能不存在的数组元素的 int 值可能存在哪些陷阱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25825308/

相关文章:

javascript - HTMLButtonElement.onclick上未捕获的ReferenceError

php - 引用 - 这个错误在 PHP 中意味着什么?

javascript - 我如何使用 php 和 Angular js 在 http 上发布 ngCart checkout 按钮?

php - Yii 从组件 Controller 请求模型

javascript - jquery传递单选按钮数组

python-3.x - 不使用try/except怎么捕捉错误?

error-handling - 在 Rust : concating results on Ok 中编写错误

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

php - 在 Woocommerce 中使用自定义选择字段触发 update_checkout

php - 提交表单后显示错误信息