如何在PHP类中正确定义数组,以防止未定义的索引错误


How to correctly define an array inside a PHP class to prevent undefined index errors?

我正在尝试一点PHP,并试图理解为什么我不断收到以下undefined index错误:

class foo {
  public static some_dict;
  public function fillSomeDict() {
    self::some_dict = array(1=>"foo",2=>"baz",4=>"cous");
  }
  public function dump() {
     $err = error_get_last();
     $type = $err["type"];
     echo self::some_dict[$type];
  }
  public function setup() {
    register_shutdown_function(array($this, "dump"));
  }
}
$x = new foo();
$x->fillSomeDict();

我的问题是,我总是在some_dict[$type]这行上得到"未定义索引"错误。我已经尝试过通过父调用(这里的示例)在__construct上填充数组,但它仍然不起作用。。。

问题:如何在PHP中正确引用此数组的元素?如何正确设置它们?

谢谢!

在将$err作为数组访问之前,应该检查它是否是数组。

检查self::$some_dict中是否有索引为$err['type']的元素(我在'echo'中这样做)

    public function dump() {
        $err = error_get_last();
        if(!is_array($err)) {
            echo 'No errors!';
            return;
        }
        echo isset(self::$some_dict[$err["type"]]) ? self::$some_dict[$err["type"]] : 'No error with index "'.$err["type"].'"';
  }

初始化变量时需要定义数组。

所以改变

 public static $some_dict;

public static $some_dict = array(1=>"foo",2=>"baz",4=>"cous");

当你调用它时,你需要使用$isset

if(isset(self::$some_dict[$err["type"]])){ echo self::$some_dict[$err["type"]]; }