PHP: To Type Hint or Not

Apparently some people think type hinting with PHP is stupid.

I don’t agree. I’ve been writing PHP since PHP version 3 and I think one of the greatest clunk factors in PHP has been that it’s loosely typed. You can never be sure that a string is a string, or is it an integer this time? Most of the time it doesn’t matter and PHP figures it out all and we go about our merry way.

But when it doesn’t work, it can lead to some ugly code needed to cast or convert or type check a variable to make sure it doesn’t throw errors or fail entirely. That, and a few other reasons are why I like type hinting with PHP.

I like to be able to write a method that will only accept a particular object. I think that sort of method contract makes the code cleaner, makes the code more readable, makes generating documentation more useful and easy, and there’s really no reason to not do it.

public function sum(Number $un, Number $deux)
{
}

That to me is more clear and descriptive than this.

public function sum($un, $deux)
{
}

If I didn’t write that method, I might have to look at the source to see what the method is expecting. Does it want numbers or does it want a Number object. Documentation could clear that up for me, but if it’s not readily available, I’ll have to examine the source code.

If programmers need to look at your source code to understand how to work with your application or library, that’s a fail.

Share Button

Leave a Reply

Your email address will not be published.