亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

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

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

它的結果是:

string(5) "Freek"
bool(true)

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

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 函數(shù)執(zhí)行結果符合預期判斷,唯獨 empty 函數(shù)返回了錯誤結果。

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

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

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

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

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

在正中應用場景下,如果你希望 empty 函數(shù)能夠正常處理變量,我們需要在類中實現(xiàn) __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 函數(shù)判斷結果為空但實際值卻為非空的原因解析,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!

相關文章

最新評論