Re: [RFC] [DISCUSSION] Type casting in array destructuring expressions

From: Date: Thu, 26 Mar 2020 12:38:52 +0000
Subject: Re: [RFC] [DISCUSSION] Type casting in array destructuring expressions
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-109333@lists.php.net to get a copy of this message
Hi Levi, Am 25.03.2020 um 21:44 schrieb Levi Morrison:
To me, this is almost a good idea. However, I would want regular type checking, not casts. Importantly, regular type checks would fit well on allowing array destructuring directly in function signatures, which would basically be a form of named parameters.
How exactly do you imagine array destructuring in function signatures with type checks? Something like: function test(['parameter1' => int $parameter1, 'parameter2' => string $parameter2) {
    // ... do something with $parameter1 and $parameter2
} Calling the function then may look like: test(['parameter1' => 100, 'parameter2' => 'Hello World']); I guess the type check then depends on the strict_types direcitve whether a call like: test(['parameter1' => 100, 'parameter2' => 100]); would trigger a TypeError or be valid and cast the value for $parameter2 to a string just like a casual function signature with a string parameter. The same behaviour would be applied to array destructuring outside of function signatures. Assumed we gather data from a CSV file: 1,Test,2002 2,Example,2010 3,Demo,2016 And we want to process the data with array destructuring like: $handle = fopen('test.csv', 'r'); while (($data = fgetcsv($handle)) !== false) {
    [int $id, string $data, int $year] = $data;
    // do something with the correctly typed variables
} The code would trigger a fatal error when strict_types are enabled. With strict_types disabled it would behave identically as the currently proposed casts. I wouldn't want the example above to trigger a TypeError even when strict_types are enabled. As a form of named parameters regular type checks should definitely preferred over a cast but for the current usage of array destructuring I think regular type checks cover different use cases (which may also exist) than my proposal. Enno

« previous php.internals (#109333) next »