Re: Vibe check: array shapes

From: 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 [email protected] to get a copy of this message

> 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)

« previous php.internals (#126530) next »