2010-03-19 83 views
12

我有時迷糊中使用它們的其中之一,如果設置了var,我應該使用哪個函數進行測試?

說我有一個名爲getmember($id)

function getmember($id) 
{ 

// now this is the confusing part 
// how do i test if a $id was set or not set? 

//solution 1 
if(empty($id)) 
{ 
return false; 
} 


// solution 2 

if(isset($id)) 
{ 
return false; 
} 

} 

函數,有時候我也不清楚,有時如果函數中的參數設置類似function($var="")

然後我做

if($var ==="") 
{ 
return false; 
} 

我應該用什麼下次isset ? empty ? or ===''

回答

10

在這裏,你走了,什麼工作完全癱瘓,當:

<? 
echo "<pre>"; 
$nullVariable = null; 

echo 'is_null($nullVariable) = ' . (is_null($nullVariable) ? 'TRUE' : 'FALSE') . "\n"; 
echo 'empty($nullVariable) = ' . (empty($nullVariable) ? 'TRUE' : 'FALSE') . "\n"; 
echo 'isset($nullVariable) = ' . (isset($nullVariable) ? 'TRUE' : 'FALSE') . "\n"; 
echo '(bool)$nullVariable = ' . ($nullVariable ? 'TRUE' : 'FALSE') . "\n\n"; 

$emptyString = ''; 

echo 'is_null($emptyString) = ' . (is_null($emptyString) ? 'TRUE' : 'FALSE') . "\n"; 
echo 'empty($emptyString) = ' . (empty($emptyString) ? 'TRUE' : 'FALSE') . "\n"; 
echo 'isset($emptyString) = ' . (isset($emptyString) ? 'TRUE' : 'FALSE') . "\n"; 
echo '(bool)$emptyString = ' . ($emptyString ? 'TRUE' : 'FALSE') . "\n\n"; 

//note that the only one that won't throw an error is isset() 
echo 'is_null($nonexistantVariable) = ' . (@is_null($nonexistantVariable) ? 'TRUE' : 'FALSE') . "\n"; 
echo 'empty($nonexistantVariable) = ' . (@empty($nonexistantVariable) ? 'TRUE' : 'FALSE') . "\n"; 
echo 'isset($nonexistantVariable) = ' . (isset($nonexistantVariable) ? 'TRUE' : 'FALSE') . "\n"; 
echo '(bool)$nonexistantVariable = ' . (@$nonexistantVariable ? 'TRUE' : 'FALSE') . "\n\n"; 
?> 

輸出:

is_null($nullVariable) = TRUE 
empty($nullVariable) = TRUE 
isset($nullVariable) = FALSE 
(bool)$nullVariable = FALSE 

is_null($emptyString) = FALSE 
empty($emptyString) = TRUE 
isset($emptyString) = TRUE 
(bool)$emptyString = FALSE 

is_null($nonexistantVariable) = TRUE 
empty($nonexistantVariable) = TRUE 
isset($nonexistantVariable) = FALSE 
(bool)$nonexistantVariable = FALSE 

當我告訴(bool)$variable以上,這是你如何能在使用它有條件的。例如,要檢查一個變量爲空或空的,你可以這樣做:

if (!$variable) 
    echo "variable is either null or empty!"; 

但它是最好用的功能,因爲它是一個有點更具可讀性。但這是你的選擇。

另外,檢查the PHP type comparison table。這基本上是我上面做的,除了更多。

+0

全面,準確,+1 – dnagirl

+0

YEPP也是從我+1感謝解釋 – streetparade

3

如果你只是想知道,如果一個變量的定義,使用isset()

如果你想看看它是否被初始化,使用is_null()

如果要比較它的價值,是別的東西,使用==

+0

'empty'比'is_null更好()'因爲有時變量初始化以零長度字符串,比如'$ X =' ';' – Andy

+0

我認爲is_null在value = null中爲true或者之前未設置? – streetparade

相關問題