(When) should I use type hinting in PHP? (When) should I use type hinting in PHP? php php

(When) should I use type hinting in PHP?


It's not about static vs dynamic typing, php is still dynamic. It's about contracts for interfaces. If you know a function requires an array as one of its parameters, force it right there in the function definition. I prefer to fail fast, rather than erroring later down in the function.

(Also note that you cant specify type hinting for bool, int, string, float, which makes sense in a dynamic context.)


You should use type hinting whenever the code in your function definitely relies on the type of the passed parameter. The code would generate an error anyway, but the type hint will give you a better error message.


The motivation of the PHP group to add type hinting was to provide people used to Java-style OOP with another feature that would make the platform more familiar, comfortable, and appealing. This, in turn, would make PHP more "enterprise ready", which would help Zend with their core business.

Marketing aside, it does have its uses. If you're writing a method that operates on a parameter in a specific way that would cause unintended (often silent) failures if the parameter was something else, then using type hinting ensures the code will break during development rather than breaking in production.