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

jp2*_*ode 1 php

该公司在代码中保留了他们的PHP错误,但我把它打开,看看为什么我的某些东西不起作用.

但是,现在我收到了数百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;    
}
Run Code Online (Sandbox Code Playgroud)

为了消除这些通知,我按照帖子为什么要检查isset()和!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;    
}
Run Code Online (Sandbox Code Playgroud)

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

如何修复代码以使其不会创建此条件?

Dem*_*335 6

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

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