我有时会混淆使用哪一个,
说我有一个名为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; }
下一次我应该使用什么?空的或===”?
在这里,你可以完整地了解什么是有效的:何时
原文链接:https://www.f2er.com/php/139382.html<? 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)$变量上面,这是你如何使用它在条件.例如,要检查变量是空值还是空值,可以这样做:
if (!$variable) echo "variable is either null or empty!";
但是最好使用一个函数,因为它有一点点可读性.但这是你的选择.
另外,检查the PHP type comparison table.这基本上是我刚刚做的上面,除了更多.