Re: Vibe check: array shapes
> On 28 Feb 2025, at 23:57, Bilge <[email protected]> wrote:
>
> Generics
Yes, I am aware that generics are being worked on. However, generics wouldn't provide
structural interfaces for arrays. At most it would provide a way to infer/define generic types for
array keys and/or values.
I guess I should've provided a code example straight away. Here's what I have in mind:
```php
declare(strict_types=1);
shape MyArray {
"id": int;
"name": string;
}
function doArrayStuff(MyArray $array) { ... }
doArrayStuff(['id' => 1, 'name' => 'Alwin']); // Works, array
conforms to shape
doArrayStuff(['id' => '1', 'name' => 'Alwin']); //
Fails, 'id' should be int
```
The best that Generics would be able to offer for arrays is:
```php
function doArrayStuff(array<string, int|string> $array) { ... }
doArrayStuff(['id' => 1, 'name' => 'Alwin']); // Works
doArrayStuff(['id' => '1', 'name' => 'Alwin']); //
Works
```
Alwin
Thread (10 messages)