PHP empty 函数误判现象与调试记录
近期在项目开发中,笔者在使用 empty 函数时遭遇了一些出乎意料的检测结果。现将整理后的调试过程分享如下。
var_dump(
$person->firstName,
empty($person->firstName)
);
具体的执行输出显示:
string(5) "Freek" bool(true)
该结果令人费解。既然变量值为字符串,为何会被判定为空?为了排查原因,我们在 $person->firstName 变量上尝试了其他检测函数:
var_dump(
$person->firstName,
empty($person->firstName),
isset($person->firstName),
is_null($person->firstName)
);
上述代码的执行结果为:
string(5) "Freek" bool(true) // empty bool(true) // isset bool(false) // is_null
译者注:此处 isset 的结果可能存在争议,实际运行中 isset 同样返回 false,可点击这里在线验证。
对比发现,isset 和 is_null 的执行结果符合预期,唯独 empty 函数给出了错误的判断。
接下来,我们查看 Person 类的具体实现代码:
class person
{ protected $attributes = [];
public function __construct(array $attributes)
{
$this->attributes = $attributes;
}
public function __get($name)
{
return $this->attributes[$name] ?? null;
}
}
从代码可见,Person 对象的成员变量是通过 __get 魔术方法从 $attributes 数组中检索得到的。
当把变量传递给普通函数时,$person->firstName 会先进行取值操作,再将结果作为参数传入。
然而,empty 并非普通函数,而是语言结构。因此,当向 $person->firstName** 传入 **empty** 时,不会先触发取值处理。它会直接检查 **$person 对象成员变量 firstName 是否真实存在。由于该变量并未在对象内部真实定义,故返回 false(即判定为空)。
在实际应用场景中,若希望 empty 能正确处理此类变量,需在类中实现 __isset 魔术方法。
class Person
{
protected $attributes = [];
public function __construct(array $attributes)
{
$this->attributes = $attributes;
}
public function __get($name)
{
return $this->attributes[$name] ?? null;
}
public function __isset($name)
{
$attribute = $this->$name;
return !empty($attribute);
}
}
当 empty 进行控制判断时,便会调用此魔术方法来决定最终结果。
再次观察修改后的输出结果:
var_dump(
$person->firstName,
empty($person->firstName)
);
新的检测结果如下:
string(5) "Freek" bool(false)
总结
以上所述是小编给大家介绍的php empty 函数判断结果为空但实际值却为非空的原因解析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对本站网站的支持!