Hack, HHVM and what it means for PHP


PHP is one of the most popular languages for web development and it's no wonder why. It's easy to setup and start writing for right away. However, that doesn't mean there's not room for improvement.

This is where Hack comes in. Hack is a language that runs on Facebook's HipHop Virtual Machine that takes the idea of the fast developement cycle of PHP and adds in some static typing and some niceties like lambda expressions and a variable number of arguments.

Here are some of the things I notcied when I started playing around with it.

(Optional) Static Types

This would probably be the biggest change. Having type annotations helps in providing some hints in the code that wouldn't be there if there weren't any.

I've seen stuff like this too many times.

function plus_one ($a) {
    return $a + 1;
function add_one ($a) { return $a . ' 1'; }

Now imagine seeing these two functions in a script in the wild. It's pretty confusing: you can't tell what these functions do based on their names. And it can get very difficult when trying to debug.

Now with type annotations:

function plus_one (int $a) : int {
    return $a + 1;

function add_one (string $a) : string {
    return $a . ' 1';

That's a bit better. There's now more information for how the functions behave and that's invaluable for debugging. Here, plus_one takes in an int and returns an int so you can make a guess that it increases a number by one.

Lambda Expressions

Callbacks are pretty handy and used everywhere. However, they can get pretty unwieldy.

Here's a pretty common thing to do: change every item in an array in the same way. Much of the time we have to do something like this:

 function increment(int $a) : int  {
     return $a + 1;

$old = array(1,2,3);
$new = array_map('increment', $old);

But instead you can do something like this:

$old = array(1,2,3);
$new = array_map(($x) ==> $x + 1, $old);

($x) ==> $x + 1 can be though of shorthand for a function that reads "take in a single argument and add one to it". That's the power of a lambda expression. Instead of defining a funciton that's going to only be used once you can write it inline and see everything that's going to happen at a glance.


One oddity about PHP is how it uses arrays. You can use arrays for a many things. $arr[0] is an indexed array,$arr["key"] is a dictionary and there are functions on arrays that let you treat them like sets. Hack attemps to add some clarity by providing some collection types like Vector and Map which would be alteratives for an indexed array and dictionary respectively.

My favorite thing about this instance are objects. That means I can add something to a Vectorintuitively with $arr->add($thing). Say goodbye to remembering all of those array functions.