问题描述
如果我这样做,我的代码似乎可以检查是否为空
It seems like my code works to check for null if I do
if ($tx)
或
if (isset($tx))
写的比较难,我为什么要写第二个?
why would I do the second one when it's harder to write?
推荐答案
我想指出,我在这里读到的每个人的回复都应该添加一个警告:
I want to point out that everyone's reponse I've read here should have one caveat added:
"isset() 将在测试已设置为 NULL 的变量时返回 FALSE" (php.net/isset).
这意味着在某些情况下,例如检查 GET 或 POST 参数,使用 isset() 足以判断变量是否已设置(因为它要么是字符串,要么是不会被设置).但是,如果 NULL 是变量的可能值(当您进入对象和更复杂的应用程序时这种情况很常见),isset() 会让您感到无所适从.
This means that in some cases, like checking for a GET or POST parameter, using isset() is enough to tell if the variable is set (because it will either be a string, or it won't be set). However, in cases where NULL is a possible value for a variable, which is fairly common when you get into objects and more complex applications, isset() leaves you high and dry.
例如(使用 PHP 5.2.6 和 Suhosin-Patch 0.9.6.2 (cli) 测试(构建时间:2008 年 8 月 17 日 09:05:31)):
For example (tested with PHP 5.2.6 with Suhosin-Patch 0.9.6.2 (cli) (built: Aug 17 2008 09:05:31)):
<?php
$a = '';
$b = NULL;
var_dump(isset($a));
var_dump(isset($b));
var_dump(isset($c));
输出:
bool(true)
bool(false)
bool(false)
谢谢,PHP!
这篇关于PHP 中的弱类型:为什么要使用 isset?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!