做php开发时候,想必在使用:empty,isset,is_null 这几个函数时候,遇到一些问题。甚至给自己的程序带来一些安全隐患的bug。很多时候,对于isset,empty都认为差不多。因此开发时候,就没有注意,一段作为流程判断时候,就出现bug问题了。 一、举例说明 <?php #不存在$test 变量 $isset= isset($test)?"test is define!":"test is undefine!"; echo "isset:$isset\r\n"; $empty=!empty($test)?"test is define!":"test is undefine!"; echo "empty:$empty\r\n"; $is_null=is_null($test)?"test is define!":"test is undefine!"; echo "is_null:$is_null\r\n";
结果出来了:empty,isset首先都会检查变量是否存在,然后对变量值进行检测。而is_null 只是直接检查变量值,是否为null,因此如果变量未定义就会出现错误! B、看下各自接收的参数是什么? isset函数参数: <?php
<br /> empty函数参数: <?php echo empty($test),empty(100),empty($b=100);
<br /> is_null函数参数: <?php echo is_null($test),is_null(100),is_null($b=100); 运行结果:没有任何错误。 比较结果出来了:empty,isset输入参数必须是一个变量(php变量是以$字符开头的),而is_null输入参数只要是能够有返回值就可以。(常量,变量,表达式等)。在php手册里面,对于他们解析是:empty,isset 是一个语言结构而非函数,因此它无法被变量函数调用。 二、概括总结isset,empty,is_null区别: <?php $a=100; $b=""; $c=null; //isset检查 echo "isset","\$a=$a",isset($a)?"define":"undefine","\r\n"; echo "isset","\$b=$b",isset($b)?"define":"undefine","\r\n"; echo "isset","\$c=$c",isset($c)?"define":"undefine","\r\n"; unset($b); echo "isset","\$b",isset($b)?"define":"undefine","\r\n"; $b=0; echo "\r\n\r\n"; //empty检查 echo "empty","\$a=$a",!empty($a)?"no empty":"empty","\r\n"; echo "empty","\$b=$b",!empty($b)?"no empty":"empty","\r\n"; echo "empty","\$c=$c",!empty($c)?"no empty":"empty","\r\n"; unset($b); echo "empty","\$b",!empty($b)?"no empty":"empty","\r\n"; $b=0; echo "\r\n\r\n"; //is_null检查 echo "is_null","\$a=$a",!is_null($a)?"no null":"null","\r\n"; echo "is_null","\$b=$b",!is_null($b)?"no null":"null","\r\n"; echo "is_null","\$c=$c",!is_null($c)?"no null":"null","\r\n"; unset($b); echo "is_null","\$b",is_null($b)?"no null":"null","\r\n";
<?php function checkNull($a) { if(array_key_exists($a,$GLOBALS)) { global $$a; if(is_null($$a)) return true; } return false; } $test=null; var_dump(checkNull("test")); var_dump(checkNull("test1")); |