【问题标题】:Expression return true, when one of elements is not set. Array of objects当元素之一未设置时,表达式返回 true。对象数组
【发布时间】:2018-09-12 12:14:32
【问题描述】:
if(isset($cat[$k]->id) && $cat[$k]->id==$nav[$lvl-1]->id) // = false 

但是

if($cat[$k]->id==$nav[$lvl-1]->id) // = true

这怎么可能?

【问题讨论】:

  • 对 null 变量的 isset 返回 false。查看文档:php.net/manual/function.isset.php
  • 不存在的值/变量被替换为null并且PHP中的两个空值相等
  • 嗨,OP,我想知道您的问题是否已得到解答?

标签: php arrays object isset


【解决方案1】:

您的代码可能是正确的,但您的语句返回错误。

你需要调试它。

我会给你写一个例子来说明如何做到这一点,包括文档。

示例:

$test1 = false;
$test2 = null;
$test3 = [];
$test4 = 'asd';
$test5 = 1;

if ($test1)
{
    echo 'Valid';
}
else
{
    echo 'False';
}
// Output: 'False'
// This is because $test1 = false. The if statement will check if $test1 is set/true and not false.

if ( ! $test2)
{
    echo 'NULL';
}
else
{
    echo 'NOT NULL';
}
// Output: 'NULL'
// $test2 is NULL/EMPTY (NULL = not valid)
// For the if( ! ..) part, will say if not.

if (is_array($test3))
{
    echo 'Is array';
}
else
{
    echo 'Is not an array';
}
// Output: 'Is array'
// [] is short for array(); $test3 is an array, so your if statement will continue as valid.

if ( ! empty($test4) || is_integer($test5))
{
    echo 'Valid';
}
else
{
    echo 'Is not valid';
}
// Output: 'Valid'
// Both $test4 and $test5 pass the if statement. Because $test4 is not empty OR $test5 is an integer.

与您的代码相关:

echo '<pre>';
var_dump($cat[$k]);
echo '</pre>';
die;

if(isset($cat[$k]->id) && $cat[$k]->id==$nav[$lvl-1]->id);

您需要“调试”您的代码。你需要设置$cat[$k]-&gt;id,如果没有设置它会返回false。

在调试时检查数据是否正确解析。

文档:


我希望向您展示如何调试代码并了解isset() 的工作原理,而不是立即给您正确的答案。如果您有任何问题,请在评论中告诉我。

祝你好运!

【讨论】:

    【解决方案2】:

    我找到了很好的解决方案:对于对象属性,最好使用函数 property_exists() - http://php.net/manual/en/function.property-exists.php

    即使属性的值为 NULL,函数 property_exists() 也会返回 TRUE。无论如何,感谢用户的 cmets,最好知道 isset() 返回 false 而不是参数的值为 NULL。

    【讨论】:

      猜你喜欢
      • 2015-07-02
      • 1970-01-01
      • 2017-10-28
      • 1970-01-01
      • 2019-08-30
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多