douhuan3448 2015-02-25 21:41
浏览 132

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

I'm trying a little PHP and am trying to understand why I keep getting an undefined index error for the following:

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();

My problem ist, I'm always getting ´undefined index´ errors on this line some_dict[$type]. I have already tried to populate the array on __construct, through the parent call (example here), but it still does not work...

Question: How do I correctly reference elements of this array in PHP? How do I set them correctly?

Thanks!

  • 写回答

2条回答 默认 最新

  • dp7311 2015-02-25 21:51
    关注

    You should check whether $err is an array before access to it as an array.

    And check whether do you have an element in self::$some_dict with index $err['type'] (i am doing this in '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"].'"';
      }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度