2014-09-23 83 views
0

這幾乎肯定是this question的重複,但我想我的問題更多的是關於常見約定/最佳實踐,給出了答案。如何檢查變量是否存在,在一次掃描中是否爲真?

例子:

if(isset($this->_available[$option]['accepts_argument']) && $this->_available[$option]['accepts_argument']) { 
    // do something 
} 

這只是醜陋。但如果我不做第一次檢查,我會得到一個php通知。我應該確保數組鍵「accepc_argument」總是存在,並且默認爲false?這樣我可以測試它是否屬實,而不是測試它是否存在?

我應該不擔心醜陋/冗長嗎?

我注意到這種模式很多在我的代碼,只是想知道人們如何處理它。我目前使用的是PHP 5.4,如果這很重要的話,但是如果我有5.5+的功能,我可以升級它。

感謝

+0

怎麼樣,如果(空($本 - > _可用[$選項] [ 'accepts_argument'])!){} – bksi 2014-09-23 00:42:13

+0

沒有替代'isset',因爲它是不是功能。它是一種語言結構。如果您嘗試將未定義的變量傳遞給自定義函數,那麼如果通過引用傳遞參數,您將得到一個警告 – 2014-09-23 00:42:22

+0

@true! – 2014-09-23 00:48:51

回答

0

這裏有一個功能我用,可以幫助你:

/** todo handle numeric values 
* @param array $array  The array from which to get the value 
* @param array $parents An array of parent keys of the value, 
*       starting with the outermost key 
* @param bool $key_exists If given, an already defined variable 
*       that is altered by reference 
* @return mixed    The requested nested value. Possibly NULL if the value 
*       is NULL or not all nested parent keys exist. 
*       $key_exists is altered by reference and is a Boolean 
*       that indicates whether all nested parent keys 
*       exist (TRUE) or not (FALSE). 
*       This allows to distinguish between the two 
*       possibilities when NULL is returned. 
*/ 
function &getValue(array &$array, array $parents, &$key_exists = NULL) 
{ 
    $ref = &$array; 
    foreach ($parents as $parent) { 
     if (is_array($ref) && array_key_exists($parent, $ref)) 
      $ref = &$ref[$parent]; 
     else { 
      $key_exists = FALSE; 
      $null = NULL; 
      return $null; 
     } 
    } 
    $key_exists = TRUE; 
    return $ref; 
} 

它得到,即使這個數組嵌套數組中的元素的值。如果路徑不存在,則返回null。魔法!

例如:

$arr = [ 
    'path' => [ 
     'of' => [ 
      'nestedValue' => 'myValue', 
     ], 
    ], 
]; 
print_r($arr); 
echo getValue($arr, array('path', 'of', 'nestedValue')); 
var_dump(getValue($arr, array('path', 'of', 'nowhere'))); 
相關問題