Shapes

Table of Contents

Does this style of PHP code look familiar?

<?hh

function why_shapes(array $arr_as_struct): array {
  if (
$arr_as_struct['id'] === '573065673A34Z') {
    
$arr_as_struct['count']++;
  }
  else {
    
$arr_as_struct['url'] = "http://google.com";
    
$arr_as_struct['count']--;
  }
  return 
$arr_as_struct;
}

function 
main_why_shapes() {
  
$my_struct = array('id' => null'url' => null'count' => 0);
  
$my_struct['id'] = '573065673A34Y';
  
$my_struct['url'] = 'http://facebook.com';

  
var_dump($my_struct);
  
$my_struct why_shapes($my_struct);
  
var_dump($my_struct);
}

main_why_shapes();

The above example will output:

array(3) {
["id"]=>
string(13) "573065673A34Y"
["url"]=>
string(19) "http://facebook.com"
["count"]=>
int(0)
}
array(3) {
["id"]=>
string(13) "573065673A34Y"
["url"]=>
string(17) "http://google.com"
["count"]=>
int(-1)
}

Since PHP does not have the concept of a structs or records, arrays are many times used to mimic a struct or record-like entity . Arrays are also used as "argument bags" to hold a bunch of arguments that will be passed to a function or method. Shapes were created to bring some structure (no pun intended) and type checking sanity to this use case.

Note:

Classes with only public fields can also be used for the same representation.

Shapes have the following general syntax:

<?hh
type MyShape 
shape('id1' => <type>, 'id2' => <type>);
function 
foo(MyShape $x): void {}

or

<?hh
newtype MyShape 
shape('id1' => <type>, 'id2' => <type>);
function 
foo(MyShape $x): void {}

Note:

Notice how shapes are declared with the HHVM keyword type or newtype. This means shapes follow the same behavior as a type alias or opaque type (e.g. underlying behavior can be accessed and changed across files for a type alias).

To Top