Monday, July 25, 2016

Can We Have Static Types in PHP without PHP 7 or HHVM?

Now that PHP 7 has been out for a while with interesting features like error handling, null coalescing operator, scalar type declarations, etc., we often hear the people still stuck with PHP 5 saying it has a weak typing system, and that things quickly become unpredictable.

Vector illustration of programmer's desktop

[author_more]

Even though this is partially true, PHP allows you to keep control of your application when you know what you're doing. Let's see some code examples to illustrate this:

function plusone($a)
{
    return $a + 1;
}

var_dump(plusone(1));
var_dump(plusone("1"));
var_dump(plusone("1 apple"));

// output

int(2)
int(2)
int(2)

Our function will increment the number passed as an argument by one. However, the second and third calls are passing a string, and the function still returns integer values. This is called string conversion. We can make sure that the user passes a numeric value through validation.

function plusone($a)
{
    if ( !is_numeric($a) )
    {
        throw new InvalidArgumentException("I can only increment numbers!", 1);
    }

    return $a + 1;
}

This will throw an InvalidArgumentException on the third call as expected. If we specify the desired type on the function prototype...

function plusone(int $a)
{
    return $a + 1;
}

var_dump(plusone(1));
var_dump(plusone("1"));
var_dump(plusone("1 apple"));

// output

PHP Catchable fatal error:  Argument 1 passed to plusone() must be an instance of int, integer given, called in /vagrant/test_at/test.php on line 7 and defined in /vagrant/test_at/test.php on line 2

This error seems a bit weird at first, because the first call to our function is using an integer!

If we read the message carefully, we'll see that the error message says "must be an instance of int" - it assumes that integer is a class, because PHP prior to version 7 only supported type hinting of classes!

Things get even more awkward with function return arguments in PHP 5. In short, we can't lock in their types automatically and we should check the expected value after the function call returns a value.

Augmented Types

Prior to the release of PHP 7, the team at Box came up with a nice idea to solve the typing safety problem on their PHP 5 application. After using assertions, type hints, etc., they decided to work on a cleaner solution for this problem.

We've seen how Facebook pushed PHP a little bit forward by launching HHVM and Hack, but the team at Box didn't want to fork the PHP source code or modify anything in the core. Their solution was to create a separate extension called augmented types to parse the method's phpDoc and assert types on runtime.

Continue reading %Can We Have Static Types in PHP without PHP 7 or HHVM?%


by Younes Rafie via SitePoint

No comments:

Post a Comment