无为清净楼资源网 Design By www.qnjia.com

最近我在一个项目中使用 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 函数判断结果为空但实际值却为非空的原因解析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

标签:
php,empty函数,php中empty函数

无为清净楼资源网 Design By www.qnjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
无为清净楼资源网 Design By www.qnjia.com