As of PHP5, type hinting is a thing. The most important distinctions are the following:
- You cannot type hint scalar/numerical, string, Resource, or Trait data.
- You can force parameters that are objects, arrays, or anonymous functions.
- You can type hint using interface names, class names,
object
keyword, array
keyword, or callable
keyword (for anonymous functions/callbacks).
- When a type hinted function or method is called with mismatched parameters, a catchable fatal error will occur (not an Exception).
- If you specify
null
as a default value, type hinting is somewhat useless.
I would suggest at least checking isset
and is_null
before running your algorithm, and I highly suggest further type checking with things like is_string
, is_int
, is_float
, etc. Type casting is also valid. Edit: this only applies for when you cannot use type hinting for a function, e.g. scalar parameters.
Returning false
or throwing an Exception are all context specific questions -- you have to determine which fits each particular function/algorithm in your package, which will include considering how someone using your code should interact with it. My favorite example of contrived Exception throwing is Sentry. I mean, look at all of those catch blocks. Maybe you'll want your code to throw that many things to provide different information, or perhaps you can return a boolean, or perhaps you can throw a new Exception("Message text")
. It's a personal choice for each piece of code. I recommend looking at potential applications where your package will be useful and see how well your package would integrate with those coding styles.
tl;dr version
The only primitives you can type hint are array
and object
. You can type cast or type check other primitives. Function/method calls with parameters that fail to satisfy type hints results in a catchable fatal error. What to do when parameters sent to your function/method are mismatched is a personal, context specific choice that nobody can definitively answer without seeing your code.
Edit: see also https://stackoverflow.com/a/5724696/2103394
empty($value)
check doesn't make sense. It will pass for anything that isn't empty (egHello world
), but will fail for0
, which is an int value. How about usingis_int()
instead?empty($value)
toisset()
and in doing so reversed the logic - this is definitely wrong in this context! As @Yannis suggests, for a required parameter you only need to checkis_int()
. Or in your case!is_int()
.