加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 如果设置了var,我应该使用哪个函数进行测试?

发布时间:2020-12-13 13:58:25 所属栏目:PHP教程 来源:网络整理
导读:我有时会混淆使用哪一个, 说我有一个名为getmember($id)的函数 function getmember($id){// now this is the confusing part // how do i test if a $id was set or not set?//solution 1if(empty($id)){return false;}// solution 2if(isset($id)){return f
我有时会混淆使用哪一个,

说我有一个名为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;
}

下一次我应该使用什么?空的或===”?

在这里,你可以完整地了解什么是有效的:何时
<?
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') . "nn";

$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') . "nn";

//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') . "nn";
?>

输出:

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.这基本上是我刚刚做的上面,除了更多.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读