我正在尝试获取 $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/