0

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
  • Your class does not have a parent. It needs to extend the parent in order to have the parent's functionality. Commented Feb 25, 2015 at 21:43
  • What is the value of $type when you get the error? Commented Feb 25, 2015 at 22:03

2 Answers 2

1

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"].'"';
  }
Sign up to request clarification or add additional context in comments.

Comments

1

You need to define your array when you initialize the variable.

So change

 public static $some_dict;

to

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

when you call it you need to use the $ and use isset

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

1 Comment

I haven't tried isset but all variations of defining $some_dict directly or via e method call, which I'd run multiple times. Not so easy....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.