rfc:generic-arrays

PHP RFC: Generic arrays

Introduction

This RFC is supplemental to the generics RFC.

This RCF proposes the addition of generic arrays and enhancements to array-related functions.

TBD: should generic versions of the standard (SPL) collection types in PHP be part of this RFC?

Proposal

This RFC proposes the addition of two generic, type-checked countersparts to the built-in array type: one with a value type, and one with key and value types.

The array keyword is overloaded, such that the following will work as expected:

$counts = array<string, int>(); // array<TKey,TValue>
$counts["kittens"] = 12;

$versions = array<float>(); // array<TValue>
$versions["php"] = 7.1;

Violating the key or value type of a type-checked array will trigger a TypeError.

The actual type-checks or type-conversions performed will depend on the strict_mode flag and normal type conversion rules.

Note that there is no generic form of the short array syntax - generic arrays can only be created explicitly by using the array keyword.

Array Type-casting

Generic arrays can be explicitly type-cast using the following syntax:

$array = [1,2,3];
 
$numbers = (array<int>) $array;

In this example, the array is fully copied, and every element is type-checked, because int is a less general element type than mixed.

Casting to a less general index or element type than that of the source array, results in creation of a new array, and keys/elements being copied. If an index or element in the source array is incompatible with the index or element types of the created generic array, a TypeError is triggered.

If an array is cast to a more general (or identical) index and element type, a lazy reference to the source array is made, identical to how PHP arrays normally work internally.

The following results in an implicit type-cast:

function tally(array<int> $numbers) {
    // ...
}
 
tally([7,8,9]);

In this case, the implicit type-cast is successful. In a case where the conversion fails, a TypeError is thrown.

Reification

TODO describe reification of generic type arguments, describe array_type() and array_key_type() functions.

Backward Incompatible Changes

No BC breaks are expected from this proposal.

Proposed PHP Version(s)

TBD

Proposed Voting Choices

For this proposal to be accepted, a 2/3 majority is required.

Patches and Tests

No patch has been written for this RFC.

rfc/generic-arrays.txt · Last modified: 2016/02/13 20:08 by mindplay