gpt4 book ai didi

php - 我应该使用哪个函数来测试 var 是否已设置?

转载 作者:行者123 更新时间:2023-12-03 01:20:35 25 4
gpt4 key购买 nike

我有时对使用其中哪一个感到困惑,

假设我有一个名为 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 时我应该使用什么?空的 ?或者===''

最佳答案

这里是什么有效以及何时有效的完整分割:

<?
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 时,这就是您在条件中使用它的方式。例如,要检查变量是否为 null 或为空,您可以执行以下操作:

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

但最好使用函数,因为它更具可读性。但这是你的选择。

另外,请检查 the PHP type comparison table 。这基本上就是我上面所做的,除了更多。

关于php - 我应该使用哪个函数来测试 var 是否已设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2478324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com