最近我在一個項目中使用 empty 時獲取到了一些意料之外的結(jié)果。下面是我處理后的調(diào)試記錄,在這里與你分享了。
var_dump( $person->firstName, empty($person->firstName) );
它的結(jié)果是:
string(5) "Freek"
bool(true)
結(jié)果出人意料。為什么變量的值為字符串,但同時會是空值呢?讓我們在 $person->firstName 變量上嘗試使用其它一些函數(shù)來進行判斷吧:
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,可以到 這里 去運行下查看結(jié)果。
isset 和 is_null 函數(shù)執(zhí)行結(jié)果符合預(yù)期判斷,唯獨 empty 函數(shù)返回了錯誤結(jié)果。
這里讓我們來看看 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 魔術(shù)方法從 $attributes
數(shù)組中檢索出來的。
當(dāng)將變量傳入一個普通函數(shù)時,$person->firstName
會先進行取值處理,然后再將獲取到的結(jié)果作為參數(shù)傳入函數(shù)內(nèi)。
但是 empty 不是一個函數(shù),而是一種數(shù)據(jù)結(jié)構(gòu)。所以當(dāng)將 $person->firstName
** 傳入 **empty** 時,并不會先進行取值處理。而是會先判斷 **$person 對象成員變量 firstName 的內(nèi)容,由于這個變量并未真實存在,所以返回 false。
在正中應(yīng)用場景下,如果你希望 empty 函數(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 進行控制判斷時,會使用這個魔術(shù)方法來判斷最終的結(jié)果。
再讓我們看看輸出結(jié)果:
var_dump( $person->firstName, empty($person->firstName) );
新的檢測結(jié)果:
string(5) "Freek"
bool(false)
總結(jié)
以上所述是小編給大家介紹的php empty 函數(shù)判斷結(jié)果為空但實際值卻為非空的原因解析,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
標(biāo)簽:巴中 山東 成都 張家口 林芝 泰州 威海 梅州
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《php empty 函數(shù)判斷結(jié)果為空但實際值卻為非空的原因解析》,本文關(guān)鍵詞 php,empty,函數(shù),判斷,結(jié),果為,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。