RE: [PHP-DEV] type hinting throwing a fatal error
| From: | Michael Sims | Date: | Mon, 08 Aug 2005 11:56:43 +0000 |
| Subject: | RE: [PHP-DEV] type hinting throwing a fatal error | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-17590@lists.php.net to get a copy of this message | ||
Derick Rethans wrote:
> Hei,
>
> currently if you pass a wrong object's type to a typehinted parameter:
[...]
> Fatal error: Argument 1 must be an instance of foo in /tmp/foo.php on
> line 3
>
> As type hinting is a new OO thing, it might perhaps make some sense to
> make this an exception instead - as this error might also happen for
> dynamic things by people who use the classes you designed. In that
> case having this fatal error to stop the whole application can be
> annoying. Opinions?
As a PHP user, I have to say I wholeheartedly agree, and I'm glad someone is
raising this issue again. The last time it was seriously discussed:
http://marc.theaimsgroup.com/?l=php-dev&m=104878782529499&w=2
was less than encouraging.
As a user who is trying to write robust code, my biggest issue is not
whether or not a type hint violation throws an exception, but whether or not
it results in an error than I can trap for. An exception would be great,
obviously, but I'd be just as happy with an E_WARNING, so at the very least
my custom error handler can catch this. As you have pointed out, it's
currently a fatal error so a user-defined error handler is not called.
I don't typically comb through my server's php error logs, since I mainly
depend on my custom error handler to let me know when one of my applications
is having problems. Because of this I have been forced to avoid using type
hints and I've actually implemented by own function to simulate type hints,
like so:
/* @param SomeObject $foo */
public function someMethod($foo) {
checkArgType($foo, 'SomeObject');
}
checkArgType() throws an exception if $foo isn't instanceof 'SomeObject'.
I would MUCH rather use type hints here. They're cleaner from a
documentation standpoint and the wtf factor is much lower. Unfortunately I
can't as long as type hint violations are fatal.
So, I would be very happy if type hint violations either threw and exception
OR triggered an E_WARNING. As Wez pointed out in
http://marc.theaimsgroup.com/?l=php-dev&m=104911187824684&w=2,
currently if
you pass the wrong number of arguments to a function/method you get an
E_WARNING (not a fatal error), so I don't see why type hint violations
shouldn't be treated similarly. It would increase their value and utility
immensely...