PHP的:使用Empty()为空字符串? [英] PHP: using empty() for empty string?

查看:134
本文介绍了PHP的:使用Empty()为空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近通过

I recently discovered this interesting article by Deceze.
But I'm a bit confused by one of its advises:

对于应该存在的变量,请勿使用空值或isset

never use empty or isset for variables that should exist

使用empty()不是测试$foo = '';是否为空的好选择吗?

Using empty() is not good choice to test if $foo = ''; is empty?

推荐答案

如果期望$foo存在,则不应使用empty(或isset).这意味着,如果根据您的程序逻辑,此时$foo应该存在:

You should not use empty (or isset) if you expect $foo to exist. That means, if according to your program logic, $foo should exist at this point:

if ($foo === '')

然后执行以下任何一项操作:

Then do not do any of these:

if (isset($foo))
if (empty($foo))

这两种语言构造抑制未定义变量的错误报告.那是他们唯一的工作.这意味着,如果您免费使用issetempty,PHP不会告诉您代码中的问题.例如:

These two language constructs suppress error reporting for undefined variables. That's their only job. That means, if you use isset or empty gratuitously, PHP won't tell you about problems in your code. For example:

$foo = $bar;
if (empty($føø)) ...

嗯,即使$bar包含期望值,为什么总是 true?因为您输错了变量名称,并且正在检查未定义变量的值.像这样编写它,是为了让PHP帮助您:

Hmm, why is this always true, even when $bar contains the expected value? Because you mistyped the variable name and you're checking the value of an undefined variable. Write it like this instead to let PHP help you:

if (!$føø) ...

注意:在线上未定义的变量føø...

Notice: undefined variable føø on line ...

条件本身是相同的,对于相同的值,== false(!)和empty会产生相同的结果.

The condition itself is the same, == false (!) and empty produce the same outcome for the same values.

如何精确检查空字符串取决于您接受或不接受的值.也许$foo === ''strlen($foo) == 0是您要查找的检查,以确保其中包含带有 something 的字符串.

How exactly to check for an empty string depends on what values you do or don't accept. Perhaps $foo === '' or strlen($foo) == 0 is the check you're looking for to ensure you have a string with something in it.

这篇关于PHP的:使用Empty()为空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆