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,
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
is_null before running your algorithm, and I highly suggest further type checking with things like
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.
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.
The only primitives you can type hint are
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