Tuesday, 18 November 2014

Strictly Research Released

Fig 1. Strict Easter Egg
After much discussion, the research conducted on introducing strict scalar parameter type hints without changing Zend has been bundled into a pecl package.

To install the strict extension for PHP5.4+ execute the following:

pecl install strict-beta

Then append the following to php.ini, or add it to a file in the config file scan directory (ie. modules.d php.d):

extension=strict.so

Windows users will soon be able to download pre-built binaries from the usual places.

The limitation

The only limitation of the extension is that scalars cannot have default values, this is because the parser treats scalar type hints as class hints. The only default value a variable with a class hint is allowed is null.

The suggestion has been made that we could support null as a special case for scalars, only accepting null as a default value, but normally raising an error when a null is passed for any parameter that does not have a default value.

I am still thinking about what to do here.

Casting

Now that strict scalars are supported, the programmer must cast parameters to the correct type.

PHP's casting semantics are ... relaxed. They never fail, and never raise an error; this can lead to some strange and unwanted behaviour.

There is an RFC in progress to address this issue in PHP7, I'm watching that RFC to see what happens.

If that RFC passes then the functions will be imported into the strict extension for the 5 series.

If that RFC fails then I will introduce a strict_cast function in the extension.

Another option is to override the built in casting mechanism with lossless-or-error casting. I intend to research the impact this has.

It is obviously going to be faster if casting is performed by operators rather than function calls, however, it might have unwanted side effects.

Return Types

There is an RFC in progress for 7 that introduces return types, when this RFC is passed I will introduce support for scalar return types in the strict extension.