advice on OO and error handling
| From: | Joel Boonstra | Date: | Tue, 29 Apr 2003 18:39:02 +0000 |
| Subject: | advice on OO and error handling | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-145683@lists.php.net to get a copy of this message | ||
Hi,
I'm working on a PHP class that needs to handle some errors gracefully.
For example, my class has a set() function for data member modification.
That function can take two scalars, or two arrays of the same size. I'd
like to do some sort of error (e.g., a PHP error message) if the
arguments are scalar/array, or two arrays of unequal size.
So I add an error handler function to my class that calls PHP's
trigger_error() function to send an E_USER_WARNING. That all works
well, except that the file and line reported are the class file, and the
line in my error reporting function, not at the point where the function
was called with bad arguments.
I have googled, but I can't see a clean way to discover the file/line of
the calling script of a PHP program. Does anyone have advice for how to
cleanly handle errors in PHP?
If that was completely unclear, here a simplified example:
1 <?
2 class foo {
3 function set($arg1, $arg2) {
4 if (count($arg1) != count($arg2)) {
5 trigger_error("sizes don't match", E_USER_WARNING);
6 }
7 }
8 }
9 $afoo = new foo();
10 $arg1 = array(1);
11 $arg2 = array(1, 2, 3);
12 $afoo->set($arg1, $arg2);
13 ?>
If I run that code, the warning produced is:
Warning: sizes don't match in /var/www/html/foo.php on line 5
However, the error really occurs on line 12, where the programmer passes
bad data into my class. Is there a clean way to get the error to output
that line, instead, thusly:
Warning: sizes don't match in /var/www/html/foo.php on line 12
Note that the the call to set() might be in a different file than the
class definition.
Sending __LINE__ along with the call to set() isn't something I would
consider to be a clean solution, as that would add a silly requirement
for the programmer accesing this class. It seems like I'm asking for
something like try/catch functionality, but that's not something PHP
provides (I don't think).
Have others run across similar problems? How did you solve them?
Thanks in advance,
--
[ joel boonstra | jboonstra@gospelcom.net ]