brunoais
brunoais

Reputation: 6836

how to use php set_error_handler for undefined indexes in arrays

I want to make a single function for set_error_handler() to deal with undefined indexes in an array with a specific name. For instance, the array is called: $products. If I have

$products = array(1 => 'a', 2 => 'b' // etc...

and later execute call:

$a = $products[0];

I get an error. I want to handle the error only for the array with the name $products and no other. How can I make that?

Please don't give me alternatives to this method of solving the problem. I already had a discussion about that and it was decided that it really is better to use this method. I must also warn that this is a super simplification of the real thing. I have already tried doing some research and nothing helped.

Upvotes: 0

Views: 173

Answers (1)

Geoff Adams
Geoff Adams

Reputation: 1119

Setting up the error handler is easy enough - examples here - but filtering based on the code which actually triggered the error just isn't achievable without some very messy regex matching (or something similar) against the error message string.

You're probably going to have to look at some other form of solution if you really require this functionality. You could use isset() to check index validity beforehand, or create an array-style class (e.g. using ArrayAccess or ArrayObject from the SPL) with some index-checking logic built-in.

I know you didn't want different solutions, but I'd be interested to find out why/how you decided that the method you're proposing really is the best way?

Upvotes: 1

Related Questions