为什么empty()对变量和数组偏移量的行为不同


Why does empty() behave differently for variable and array offset?

我有一段代码,我不理解它的行为。TRUE值在变量的不同副本中传递给empty()时会给出不同的结果。

var_dump($this->controller->type['Company']['is_active']); // bool(true)

属性$controller是具有$type属性的对象,该属性是多数组。is_active的值为bool(true)

empty()的结果应该是什么?

var_dump(!empty($this->controller->type['Company']['is_active'])); //false

好的,让我们创建一个副本

$temp = $this->controller->type['Company']['is_active']; var_dump(!empty($temp)); //true

hmmm不同的结果?

var_dump($this->controller->type['Company']['is_active'] === $temp);//true

选角怎么样?

var_dump(!empty((int)$this->controller->type['Company']['is_active'])); //true

有人能解释一下这种行为吗?

请参阅php手册,http://php.net/manual/en/function.empty.php

如果var存在并且具有非空的非零值,则返回FALSE。否则返回TRUE。

请注意,empty适用于pass-by-variable,而不是pass-by-value。

以下内容被认为是空的:

  • ""(空字符串)
  • 0(0为整数)
  • 0.0(0为浮点)
  • "0"(0作为字符串)
  • NULL
  • FALSE
  • array()(空数组)
  • $var;(已声明的变量,但没有值)