2014-01-20 85 views
1

該公司保持其代碼中的PHP錯誤被抑制,但我turned it on看到爲什麼我的東西不工作。isset()和empty()似乎無法修復「未定義索引」通知

但是,現在我收到數百個Undefined index消息,我想關閉以便我可以從我的代碼中找到消息。

這裏,讓許多錯誤一個特定塊:

final public function getAttribute($name) { 
    $value = ''; 
    if(is_array($this->attributes[$name]) === false) { // Notice: Undefined index: name 
    $value = trim($this->attributes[$name]); 
    } else { 
    $value = trim(implode(' ', $this->attributes[$name])); 
    } 
    return $value;  
} 

爲了消除這些通知,我也跟着後Why check both isset() and !empty()把它寫這樣的:

final public function getAttribute($name='') { 
    if (!isset($name) || empty($name)) { 
    return ''; 
    } 
    $value = ''; 
    if(is_array($this->attributes[$name]) === false) { // Notice: Undefined index: name 
    $value = trim($this->attributes[$name]); 
    } else { 
    $value = trim(implode(' ', $this->attributes[$name])); 
    } 
    return $value;  
} 

我仍然得到通知,和在同一個地方。

我如何修復的代碼,以便它不會創建此條件?

+0

你的PHP大師們真的很厲害! – jp2code

回答

4

您沒有使用正確的變量進行檢查。您需要檢查數組的索引是否存在。

final public function getAttribute($name='') { 
    if (!isset($this->attributes[$name]) || empty($this->attributes[$name])) { 
    return ''; 
    } 
    // ... 
} 
1

這不會引發未定義指數:

[...] 
if (isset($this->attributes[$name])) { 
    // The key $name is set in $this->attributes 
} 
else { 
    // The key is not set 
} 
0
if (!isset($this->attributes[$name])) { 
    return NULL; 
} 

上面的代碼應該這樣做。

2

嘗試isset在你的第二塊

0

使用空的第一個($這個 - >屬性[$名稱]),因爲isset將拋出未定義的錯誤,如果索引不存在,空決不會做,像:

if (empty($name) && !isset($name)) { 
    return ''; 
} 

如果值已經設置但是等於'',o或false,則使用AND將防止返回。

如果您想要返回值如果值爲true,則使用某個字符串或值,只需使用空白。不需要使用isset。

+0

我相信你的關於'isset()'拋出錯誤的陳述是不正確的。 'isset()'的目的是檢查變量是否被定義;這似乎違背了它的設計,在這方面拋出了一個錯誤。 '空'也不會。無論哪種方式,這不是他的問題的屬性,因爲它不是關注所設置的「$ name」變量,而是它所代表的索引關鍵字。 – Demonslay335

+1

是的,但是如果isset被用來測試一個帶有未知鍵的關聯數組,你將得到錯誤,如果使用空而不是發生錯誤 – jvicab

+0

'isset()'不會拋出錯誤,它被設計爲檢查變量是否存在,在這種情況下,該變量是數組的關鍵字。我已經使用以下代碼進行了測試,並且只在最後一個(不帶'empty()'或'isset()')時獲得了E_NOTICE:error_reporting(E_ALL | E_STRICT); $ arr = array('foo'=>'bar'); var_dump(isset($ arr ['baz']));然而,在檢查兩者的手冊後,我確實看到'empty()'更適合了。「(空)對於這種情況,因爲它本質上與'isset()'在內部完全相同;我學到了一些東西。 – Demonslay335