Pages

Wednesday, March 26, 2014

Arrays

Arrays 

The Hack language guidance is to use collections whenever and wherever possible. However, 100% usage of collections is obviously not realistic given how much arrays are used in various codebases (i.e., arrays were the "collection" type before collections). And there just may be legitimate use cases for an array. Here is how Hack handles arrays:
  • Use arrays in the normal, PHP way. (e.g., array).
  • Use an explicitly typed array, indexed by integers, where the value of the array has one and only one type. (e.g,array<someType>).
  • Use an explicitly typed array, indexed by an int or string , where the value of the array has one and only one type. (e.g., array<string, someType>).
  • Use a generic array, indexed by integers, where the value ofT can be of any type. (e.g., array<T>).
  • Use a generic array, indexed by an int or string, where the value of T can be of any type upon instantiation. (e.g., array<int, Tv> or array<string, Tv>).
Note:
Actually, PHP allows array keys to be floats or objects. With floats, the key is truncated to an integer. Hack allowsfloat keys; however, they are not *officially* supported.
Arrays are handled with a bit more restriction in // strict mode. Code that is written in strict mode can use arrays, but they must be typed (e.g., array<string>when used as class members, function/method parameters or return types.
Here is a code example expressing some of the Hack array constructs:
<?hh
class Foo {}
class 
HackArrays<T> {
  private array 
$arr null;
  private array<
T$arr2 null;
  private array<
stringstring$arr3 null;

  public function 
__construct(T $data) {
    
$this->arr2[0] = $data;
  }

  public function 
bar(T $data): void {
    
$this->arr = array();
    
var_dump($this->arr);
    
$this->arr2[] = $data;
    
var_dump($this->arr2);
    
$this->arr3["hi"] = new Foo();
    
var_dump($this->arr3);
  }
}

function 
main_arr() {
  
$ha = new HackArrays("Facebook");
  
$ha->bar("Food");
}
main_arr();
The above example will output:
array(0) {
}
array(2) {
  [0]=>
    string(8) "Facebook"
  [1]=>
    string(4) "Food"
}
array(1) {
  ["hi"]=>
    object(Foo)#2 (0) {
    }
}
A "map" is the most associative for an array. In other words, Hack disallows array<int, int, int>.

No comments:

Post a Comment