exception - Extending TypeError -
php7 introduced typeerror "exception" (i know implements throwable rather extends exception it's not strictly speaking exception, behave in same way far can tell) gets thrown if enable strict mode function parameter type hinting.
declare (strict_types = 1); function square (int $val) : int { return $val * $val; } var_dump (square ("123"));
the above code should throw typeerror, can optionally catch , attempt recover or terminate execution, depending on appropriate course of action take.
however, typeerror seems bit generic, , nice if able extend convey bit more information failure occurred:
class typenotinterror extends typeerror {} // throw when int expected class typenotfloaterror extends typeerror {} // throw when float expected class typenotstringerror extends typeerror {} // throw when string expected // etc
it should possible extend typeerror because php documentation doesn't state it's final class. however, while can extend typeerror there doesn't seem mechanism allows throw child of typeerror without manually throwing 1 inside function. typeerror thrown engine if pass in invalid parameter type, ability extend typeerror seems pretty limited me.
is possible tell php sort of typeerror subclass function/method should throw if passed invalid parameter type? if so, how?
Comments
Post a Comment