最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

php empty 函數(shù)判斷結(jié)果為空但實(shí)際值卻為非空的原因解析

 更新時(shí)間:2018年05月28日 10:10:17   作者:PHP ZENDO  
這篇文章主要介紹了php empty 函數(shù)判斷結(jié)果為空但實(shí)際值卻為非空的原因解析,下面是腳本之家小編處理之后的調(diào)試記錄,分享到腳本之家平臺(tái),感興趣的朋友一起看看

最近我在一個(gè)項(xiàng)目中使用 empty 時(shí)獲取到了一些意料之外的結(jié)果。下面是我處理后的調(diào)試記錄,在這里與你分享了。

var_dump(
  $person->firstName,
  empty($person->firstName)
);

它的結(jié)果是:

string(5) "Freek"
bool(true)

結(jié)果出人意料。為什么變量的值為字符串,但同時(shí)會(huì)是空值呢?讓我們?cè)?$person->firstName 變量上嘗試使用其它一些函數(shù)來進(jìn)行判斷吧:

var_dump(
  $person->firstName,
  empty($person->firstName),
  isset($person->firstName),
  is_null($person->firstName)
);

以上結(jié)果為:

string(5) "Freek"
bool(true) // empty
bool(true) // isset
bool(false) // is_null

譯者注:這邊的結(jié)果可能存在問題 isset 的結(jié)果同樣為 false,可以到 這里 去運(yùn)行下查看結(jié)果。

isset 和 is_null 函數(shù)執(zhí)行結(jié)果符合預(yù)期判斷,唯獨(dú) empty 函數(shù)返回了錯(cuò)誤結(jié)果。

這里讓我們來看看 person 類的實(shí)現(xiàn)代碼吧:

class person
{  protected $attributes = [];
  public function __construct(array $attributes)
  {
    $this->attributes = $attributes;
  }
  public function __get($name)
  {
    return $this->attributes[$name] ?? null;
  }
}

從上述代碼我們可以看到 Person 對(duì)象的成員變量是通過 __get 魔術(shù)方法從 $attributes 數(shù)組中檢索出來的。

當(dāng)將變量傳入一個(gè)普通函數(shù)時(shí),$person->firstName 會(huì)先進(jìn)行取值處理,然后再將獲取到的結(jié)果作為參數(shù)傳入函數(shù)內(nèi)。

但是 empty 不是一個(gè)函數(shù),而是一種數(shù)據(jù)結(jié)構(gòu)。所以當(dāng)將 $person->firstName** 傳入 **empty** 時(shí),并不會(huì)先進(jìn)行取值處理。而是會(huì)先判斷 **$person 對(duì)象成員變量 firstName 的內(nèi)容,由于這個(gè)變量并未真實(shí)存在,所以返回 false。

在正中應(yīng)用場(chǎng)景下,如果你希望 empty 函數(shù)能夠正常處理變量,我們需要在類中實(shí)現(xiàn) __isset 魔術(shù)方法。

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);
  }
}

這是當(dāng) empty 進(jìn)行控制判斷時(shí),會(huì)使用這個(gè)魔術(shù)方法來判斷最終的結(jié)果。

再讓我們看看輸出結(jié)果:

var_dump(
  $person->firstName, 
  empty($person->firstName)
);

新的檢測(cè)結(jié)果:

string(5) "Freek"
bool(false)

總結(jié)

以上所述是小編給大家介紹的php empty 函數(shù)判斷結(jié)果為空但實(shí)際值卻為非空的原因解析,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論

南昌市| 临漳县| 嵊泗县| 佛教| 大厂| 江山市| 开封县| 年辖:市辖区| 襄汾县| 沿河| 黎川县| 平阴县| 北京市| 晋州市| 新疆| 佛山市| 疏勒县| 鄄城县| 深泽县| 泰宁县| 布拖县| 西藏| 泸州市| 三都| 正定县| 吴江市| 天峻县| 周宁县| 兴化市| 普安县| 高台县| 葫芦岛市| 奉化市| 廉江市| 句容市| 静海县| 容城县| 山阳县| 安义县| 格尔木市| 安化县|