php empty,isset,is_null比較(差別與異同)

作php開發時候,想必在使用:empty,isset,is_null  這幾個函數時候,遇到一些問題。甚至給本身的程序帶來一些安全隱患的bug。不少時候,對於isset,empty都認爲差很少。所以開發時候,就沒有注 意,一段做爲流程判斷時候,就出現bug問題了。php

 

 

1、舉例說明html

A.一個變量沒有定義,咱們該怎麼樣去判斷呢?安全

 

<?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";

 

測試結果是:函數

image

結果出來了:empty,isset首先都會檢查變量是否存在,而後對變量值進行檢測。而is_null 只是直接檢查變量值,是否爲null,所以若是變量未定義就會出現錯誤!post

B、看下各自接收的參數是什麼?測試

isset函數參數:spa

<?php
$test=100;
echo isset($test),isset(100),$isset($b=100); code

 

<br />
<b>Parse error</b>:  parse error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '$' in <b>PHPDocument3</b> on line <b>3</b><br /> htm

empty函數參數: 對象

<?php
$test=100;

echo empty($test),empty(100),empty($b=100);

 

<br />
<b>Parse error</b>:  parse error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '$' in <b>PHPDocument3</b> on line <b>3</b><br />

is_null函數參數:

<?php
$test=100;

echo is_null($test),is_null(100),is_null($b=100);

運行結果:沒有任何錯誤。

比較結果出來了:empty,isset輸入參數必須是一個變量(php變量是 以$字符開頭的),而is_null輸入參數只要是可以有返回值就能夠。(常量,變量,表達式等)。在php手冊裏面,對於他們解析 是:empty,isset 是一個語言結構而非函數,所以它沒法被變量函數調用。

 

2、歸納總結isset,empty,is_null區別:

剛纔介紹的:檢查變量,以及參數類型,這個是這3個函數不一樣之處的基礎,也是最容易被忽視的。看到網上有不少對這個3個函數進行比較文章。不多涉及這些。下面我要說的,是在都檢查已存在變量狀況下,不一樣之處。

實例:

<?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";

 

   

image

經過上面這個簡單測試,咱們能夠大致知道,當一個變量存在狀況下:isset,empty,is_null檢測,獲得值狀況了。上面沒有舉例更多變量。其實測試發現:

empty

若是 變量 是非空或非零的值,則 empty() 返回 FALSE。換句話說,""、0、"0"、NULLFALSE、array()、var $var、未定義; 以及沒有任何屬性的對象都將被認爲是空的,若是 var 爲空,則返回 TRUE

isset

若是 變量 存在(非NULL)則返回 TRUE,不然返回 FALSE(包括未定義)。變量值設置爲:null,返回也是false;unset一個變量後,變量被取消了。注意,isset對於NULL值變量,特殊處理。

is_null

檢測傳入值【值,變量,表達式是不是null,只有一個變量定義了,且它的值是null,它才返回TRUE . 其它都返回 FALSE 【未定義變量傳入後會出錯!】.

 

疑問:怎麼樣判斷一個變量被設置了,而且值爲NULL呢?

經過上面比較,估計你們與我同樣,會有這個問題浮如今腦海裏面。 檢測一個變量是不是null 能夠用:is_null,但若是變量未定義用它檢測會出錯。所以,咱們想到,檢測變量是否認義能夠用:isset,可是若是一個變量值是:null, 則它會返回false . 哈哈,這個問題怎麼樣解決呢?等待你們分享……

分類: php
相關文章
相關標籤/搜索