问题
Is it OK to use @ when extracting a possibly missing value from a PHP array? Example:
$value = @$array['possibly_missing_key'];
The intended behavior:
if (isset($array['possibly_missing_key'])) {
$value = $array['possibly_missing_key'];
} else {
$value = null;
}
I want to know, before spreading the usage pattern.
回答1:
The @
operator suppresses error messages, and using it potentially sets up your code for other errors and unexpected behavior that end up hard to track down. Thus it's most certainly an antipattern.
Thus, I would very much prefer the second bit. It makes it much clearer
- that it may not be present in the array, and
- what the default value is if it's not present
To make it more concise you can use the ternary conditional operator ?:
, as seen in Mark Baker's answer. Slightly less code and more symbols but the meaning is well-recognized.
回答2:
Actually the isset
variation is the anti-pattern. If you just use isset($var)?$var:NULL
with the intention to suppress the "error", then you've achieved nothing over using the proper syntax for suppressing errors. It has the same outcome, yet is less readable.
People are arguing for that because of perceived "cleanliness" and because using isset is a micro optimization. Avoiding @
and using isset as syntactic salt replacement is just cargo cult programming.
回答3:
Or
$value = (isset($array['possibly_missing_key'])) ? $array['possibly_missing_key']: null;
回答4:
Ignoring warnings is definitely an antipattern; so yes, it's an anti-pattern (and I can guarantee that if you learn to suppress warnings, one of them will come back and bite you in the posterior, if not worse).
Also, while the second version is more verbose, it gives the uninitialized variable a known state (or can be used to handle the problem, if the variable is supposed to be filled).
回答5:
The third option:
$value = (isset($array['key']) ? $array['key'] : null);
I know this doesn't directly answer the question; I would have put it as a comment, except it really needed to be formatted.
The idea here is that if you're trying to make your code shorter by using a one-liner instead of an if-else block, then you can still get it into a succinct one-liner using a ternary operator, giving you the best of both worlds.
回答6:
The second block of code (or Mark Baker's alternative which will work exactly the same) is better. I'm not entirely sure about PHP, but in many other programming languages, to simply ignore a variable would almost definitely throw an error. At least with the second block you are initializing the variable to some value or memory location.
Error suppression should be more commonly used if you expect a function to throw an expected error in the end-product (however, much of the time this will not be the case).
Good luck!
Dennis M.
来源:https://stackoverflow.com/questions/4441528/is-arraypossibly-missing-key-an-anti-pattern