A couple of days ago Nikita Popov gave a nice overview about the discussion about type hints for scalar types in PHP called Scalar type hinting is harder than you think. He came up with his own alternative called Strict Weak Type Hinting. From the options in his article it seems by far the most sensible, but I think it can do with one improvement.
For starters, here is Nikita's Strict Weak Type Hinting. It does weak type hinting with strict validation:
- <?php
- function foo(int $i) {
- var_dump($i);
- }
- foo(1); // int(1)
- foo(1.0); // float(1.0)
- foo("1"); // string(1) "1"
- foo(1.5); // fatal error: int expected, float given
- foo(array()); // fatal error: int expected, array given
- foo("hi"); // fatal error: int expected, string given
In this case you can still pass in strings or floats to a parameter hinted as int but only if they losslessly convert to an int. A very sensible thing to do, but I miss one thing: I hinted the function as an int, so I want an int. I would prefer that the Strict Weak Type Hint also cast the parameter after it passes validation. Here's what that would look like:
- <?php
- function foo(int $i) {
- var_dump($i);
- }
- foo(1); // int(1)
- foo(1.0); // int(1)
- foo("1"); // int(1)
- foo(1.5); // fatal error: int expected, float given
- foo(array()); // fatal error: int expected, array given
- foo("hi"); // fatal error: int expected, string given
Your thoughts?
Comments
#1 Nikita Popov (http://nikic.github.com)
In any case, this kind of type hints are currently being discussed on the internals mailing list. The current proposal is to base them of the behavior of zend_parser_parameters (which is how internal functions accept parameters). zpp does strict-enough validation to be a sensible choice.
#2 Sander Marechal (http://www.jejik.com)
Comments have been retired for this article.