A PHP type hinting alternative

by Sander Marechal

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:

  1. <?php
  2. function foo(int $i) {
  3.     var_dump($i);
  4. }
  5. foo(1);       // int(1)
  6. foo(1.0);     // float(1.0)
  7. foo("1");     // string(1) "1"
  8.  
  9. foo(1.5);     // fatal error: int expected, float given
  10. foo(array()); // fatal error: int expected, array given
  11. 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:

  1. <?php
  2. function foo(int $i) {
  3.     var_dump($i);
  4. }
  5. foo(1);       // int(1)
  6. foo(1.0);     // int(1)
  7. foo("1");     // int(1)
  8.  
  9. foo(1.5);     // fatal error: int expected, float given
  10. foo(array()); // fatal error: int expected, array given
  11. foo("hi");    // fatal error: int expected, string given

Your thoughts?

Creative Commons Attribution-ShareAlike

Comments

#1 Nikita Popov (http://nikic.github.com)

I realized shortly after writing the article that this is indeed a better option. I was imagining problems with the casts + references that didn't actually exist (well, they do exist, but they are less serious than I thought).

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)

I am not currently subscribed to the php internals mailinglist, but I'll have a look. Thanks!

Comments have been retired for this article.