1 minute read

Hack introduced a concept called Shapes. It is an object like the associative PHP array but with predefined array keys. If you are familiar with C you might think of a shape like a struct. So what is the use case for this? Why should we complicate things with Shapes when we already doing fine with arrays?

The main drawbacks of using arrays are that you can’t type check the array values and you can’t be sure if an array key is defined.

type HtmlTag = shape('name'=>string, 'count'=>int);

function printInfo(HtmlTag $tag): void {
  echo "We found ".$tag['count']." tags of type ".$tag['name'];

printInfo(shape('name'=>'h2', 'count'=>3));

To define a shape you use the type or newtype keyword. They follow the same rules as the type aliasing. If you use newtype when defining a shape it will only be valid in the same file. You will get Hack errors if you are trying to use the shape in another file.

Likewise if you define a shape with two integers and you use it with string you will hear Hack complain. But the code will run on HHVM. Because in HHVM a shape is just an array and arrays don’t have types.


You may define your shapes with generics. It works exactly as you may expect. =)

type Point<T> = shape ('x' => T, 'y' => T);



Leave a Comment