php empty 函数判断结果为空但实际值却为非空的原因解析

(编辑:jimmy 日期: 2025/7/6 浏览:2)

最近我在一个项目中使用 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 的结果同样为 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] "htmlcode">
class Person
{
  protected $attributes = [];
  public function __construct(array $attributes)
  {
    $this->attributes = $attributes;
  }
  public function __get($name)
  {
    return $this->attributes[$name] "htmlcode">
var_dump(
  $person->firstName, 
  empty($person->firstName)
);

新的检测结果:

string(5) "Freek"
bool(false)

总结

以上所述是小编给大家介绍的php empty 函数判断结果为空但实际值却为非空的原因解析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

一句话新闻

Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。