-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Description
This is a part of the Hack array proposal
A vec
array is a container whose keys are zero-based continuous integers. This mirrors the behavior of the Vector
class. This will be an array at runtime with extra restrictions to allow it to be used safely like a Vector
from the type checkers perspective. This focuses mainly on the desired runtime behavior, but if there are questions for how it will interact with the type checker I'll be happy to discuss.
Literal Constructor
A vec
is constructed using the literal expression vec[]
.
$vec = vec[]; // Empty vec-array
$vec = vec['a', 'b', 'c']; // vec-array of 3 elements
This is a static expression, so it can be used in a static initializer.
class C {
public static $vec = vec['a', 'b', 'c'];
}
Traversable Constructor
A vec
can also be constructed from any Traversable
type, using the traversable constructor.
$array = array('a', 'b', 'c');
$vec = vec($array); // constructs vec-array from another array
Adding Elements
To preserve the property of having continuous integer keys new elements can only be added to a vec
using the array append operator.
$vec = vec[];
$vec[] = 1; // Allowed
$vec[0] = 2; // Allowed
$vec[10] = 3; // Error: 10 is out of bounds for the vec-array
Removing Elements
Using unset on a vec
type will demote it to the dict
type. If you want to preserve the vec
property then you will need to use the various array functions that operate at the beginning or end of an array such as array_pop
, array_push
, array_shift
, array_unshift
, etc.
$vec = vec[1, 2, 3, 4];
array_pop($vec); // Now vec[1, 2, 3]
array_shift($vec); // Now vec[2, 3]
unset($vec[1]); // unsetting changes a vec to a dict[ 0 => 2]