问题描述
似乎我的代码可以检查是否为空
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:
如果测试已设置为NULL的变量,则isset()将返回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.
例如(使用Suhosin-Patch 0.9.6.2(cli)在PHP 5.2.6上进行测试(内置: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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!