Wednesday, 12 November 2014

Strictly Research Continued

Fig 1. Strict Easter Egg
This week I have been experimenting with adding strict scalar type hints to PHP7 via an extension.

Scalar type hints are something that some people want, and they have good reason to want them, but I think the majority can live without them.

Internals don't seem to be able to agree on the best way to implement scalar type hints, there have been multiple RFC discussions and implementations.

The first try at an extension used auto-boxing and casting magic, and was rather slow.

The latest revision doesn't use any auto-boxing, casting, or exceptions.

This means that the following code:
function test(integer $int, 
              double $dbl, 
              boolean $bool, 
              string $str, 
              resource $fp) {

    var_dump($int, $dbl, $bool, $str, $fp);
}

test(1, 2.2, true, "four", STDIN);

Will work as expected, without the need to cast parameters to their scalar types in the function body.

Zend emits a recoverable error when a type mismatch occurs, using exceptions was therefore dropped in favour of being compatible with Zend, and expectations.

This is a much faster and much simpler implementation, and should be forward compatible with Zend getting strict scalar type hints at some time in the (distant) future.

The strict extension could also define a strict_cast utility function for lossless-or-error casting, we'll see what happens next.

The extension is available here.

3 comments:

  1. Strict type-hinting would be useful if they were actually boxed in classes and provide useful methods. For example, I could do $str = $str->toUpperCase();. Otherwise, efforts does not worth benefits.

    ReplyDelete
  2. The problem is that the autoboxing approach is very slow (see first strictly research post).

    There is a way to introduce scalar methods without a huge performance penalty, but it's a separate issue.

    ReplyDelete
    Replies
    1. I've always been against autoboxing in php (besides being slow it introduces more inconsistency php programmers will potentially create). What I suggest is something like extension methods in C#.

      Delete