2014-09-23 66 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'))); 
相关问题