The docs are pretty light. The interface looks almost identical to an array.
When should I prefer a dict?
The docs are pretty light. The interface looks almost identical to an array.
When should I prefer a dict?
Arrays in php are meant to be both dictionaries and vectors. That's very confusing. Also in arrays, there is key coercion to integer. Which is more confusing.
Hack dicts are meant to remove the ambiguity and fix the problem with the keys.
To expand a bit:
array<string, Tv>
is a lie, and breaks Hack's type system. array_keys(['123' => 'bar'])[0]
is an int
, not a string
. This isn't the case for dict
or keyset
.A more interesting question is "Hack arrays" (vec
, dict
, keyset
), vs "Hack collections" (Map
, Set
, Vector
) and their const/immutable relatives. This is pretty contentious.
The main differences are that they are objects, not values; this effectively means that functions you pass them to can mutate them, whereas vec/dict/keyset act as if they are copy-on-write. The copy-on-write behavior is usually desired, but occasionally, object behavior is desired.
This is where it becomes contentious:
- some argue that if you want object-like semantics, you should use Hack Collections
- I personally think it's better to wrap it in a 'Ref' class: e.g. class Ref<T> { public function __construct(public T $value) {}
- and operate on $ref->value
using the standard API; this lets you use the same API (the HSL) for both, rather than the slightly different one that collection objects have