isset()和empty()似乎没有修复“未定义的索引”通知

时间:2014-01-20 22:50:05

标签: php

该公司在代码中保留了他们的PHP错误,但我turned it on了解为什么我的某些东西无效。

但是,现在我收到了数百封Undefined index消息,我想关闭这些消息,以便我可以从MY代码中找到消息。

这是一个会产生许多错误的特定块:

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;    
}

我仍然收到通知,并在同一个地方。

如何修复代码,以便它不会创建此条件?

5 个答案:

答案 0 :(得分:5)

您没有使用正确的变量进行检查。您需要检查数组的索引是否存在。

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

答案 1 :(得分:2)

在第二个块中尝试isset($ this->属性[$ name])

答案 2 :(得分:1)

这不会抛出未定义的索引:

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

答案 3 :(得分:0)

if (!isset($this->attributes[$name])) {
  return NULL;
}

上面的代码应该这样做。

答案 4 :(得分:-1)

首先使用空,因为如果索引不存在,isset将抛出未定义的错误,而且将永远不会执行,如:

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

如果值已经设置但等于'',o或false,则在此处使用AND将阻止返回。

如果要返回值,如果值为true,则返回一些字符串或值,只需使用empty。不需要使用isset。