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!
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"].'"';
}
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"]]; }