简体   繁体   English

PHP检查非空的更好方法?

[英]PHP a better way for check non-empty?

The common way for check non-empty var is: 检查非空var的常用方法是:

if (!empty($var)) { ... }

Why can't we just use: 我们为什么不能只使用:

if ($var) { ... }

They're the same actually, right? 他们实际上是一样的,对吗?

Ref: http://php.net/manual/types.comparisons.php 参考: http : //php.net/manual/types.comparisons.php

!empty($var) is exactly the same as just $var , except that with empty no error will be thrown if $var doesn't exist. !empty($var)是完全一样的只是$var ,除了具有empty ,如果没有错误将被抛出$var不存在。 empty is more or less shorthand for !isset($var) || !$var empty或多或少是!isset($var) || !$var简写!isset($var) || !$var !isset($var) || !$var . !isset($var) || !$var

You should never use empty if you expect your variable to exist, because then you're just needlessly suppressing error reporting. 如果您希望变量存在,则永远不要使用empty ,因为那样您就不必要地抑制错误报告了。 Only use empty if you legitimately expect the variable to possibly not exist. 仅当您合理地预期该变量可能不存在时才使用empty This should rarely if ever be the case, if you're initialising your variables properly. 如果正确初始化变量,这种情况很少会出现。

See The Definitive Guide To PHP's isset And empty for an in-depth discussion of this. 有关此内容的深入讨论,请参见《 PHP isset和空的权威指南》

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM