On Wed, Jun 26, 2024, at 22:56, Casper Langemeijer wrote:
>
> On Wed, Jun 26, 2024, at 21:59, Richard Miles wrote:
>> I think we should have typed arrays in PHP.
>
> Yes! I cannot stand sitting through conference talks on 'generics' that only talk
> about 'collections'. This could be solved if we had typed arrays. If anything we would get
> better talks on Generics. :-)
>
> Arrays of a type is one of the last cases where I need docblocks to tell my editor about the
> types.
>
> In my opinion, even if we would have some implementation of generics, having typed arrays with
> a simple syntax would be awesome.
>
> A syntax suggestion:
>
> $array = stdClass[];
> class A {
> public stdClass[] $array;
> }
>
> Adding an invalid array member should throw TypeError.
>
> I know there are way more edge-case situations to think of (for example: if class B extends A,
> $b is of type B[], but holds only A's, can $b be assigned as value of public A[] $a ?)
>
>> Generics or bust.
>
> I do not understand the reasoning behind that. Is it because we really want generics, but when
> the 95% use-case is solved we fear that there would not be enough momentum to get that? I'd
> love to have generics too, but a very simple array syntax would in my opinion still add a lot of
> value, even if we already had generics.
>
You actually just gave me an evil idea on how to get generics in userland… unfortunately it is bed
time as I have an early train to catch in the morning. I will stew on it, but here is the gist:
Create a class that generates a typed collection when accessed via array, such that (new
InternalTypedArray)['int'] produces a class that acts like an array but only accepts ints.
Using the composer file loading key, load a file that contains:
define('TypedArray', new InternalTypedArray);
You can now use $arr = TypedArray['MyType']
Could be interesting and I wouldn’t be surprised if it hasn’t been done before.
— Rob