Re: Vibe check: array shapes
| From: | Alwin Garside | Date: | Fri, 28 Feb 2025 23:21:31 +0000 |
| Subject: | Re: Vibe check: array shapes | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-126530@lists.php.net to get a copy of this message | ||
> On 28 Feb 2025, at 23:57, Bilge <bilge@scriptfusion.com> 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