最近我在一個項目中使用 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] ?? 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 函數判斷結果為空但實際值卻為非空的原因解析,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
您可能感興趣的文章:- 深入理解PHP中的empty和isset函數
- PHP5.5和之前的版本empty函數的不同之處
- PHP empty函數報錯解決辦法
- PHP表單驗證的3個函數ISSET()、empty()、is_numeric()的使用方法
- php empty函數判斷mysql表單是否為空
- php empty函數 使用說明