rfc:typecast_array_desctructuring
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revision | Next revisionBoth sides next revision | ||
rfc:typecast_array_desctructuring [2020/04/07 09:49] – Add target version wol-soft | rfc:typecast_array_desctructuring [2020/04/08 09:26] – Added motivation and discussion section wol-soft | ||
---|---|---|---|
Line 9: | Line 9: | ||
===== Introduction ===== | ===== Introduction ===== | ||
Adds the possibility to cast values while using array or list destructuring expressions. | Adds the possibility to cast values while using array or list destructuring expressions. | ||
+ | |||
+ | ===== Motivation ===== | ||
+ | |||
+ | This proposal aims at type casts when working with data from a untyped source (eg. iterating over a CSV file, XML without a XSD defining the types of the elements). This data can often be handled in an elegant way using the existing capabilities of array destructuring. While simple variable assignments can be casted during the assignment this isn't possible during assignments via array destructuring. This proposal adds a new syntax for casting in array assignments. An example when handling a CSV file may look like: | ||
+ | |||
+ | < | ||
+ | 1,Test,2002 | ||
+ | 2, | ||
+ | 3,Demo,2016 | ||
+ | </ | ||
+ | |||
+ | <code php> | ||
+ | $handle = fopen(' | ||
+ | while (($data = fgetcsv($handle)) !== false) { | ||
+ | [(int) $id, (string) $data, (int) $year] = $data; | ||
+ | // ... | ||
+ | } | ||
+ | </ | ||
===== Proposal ===== | ===== Proposal ===== | ||
Line 92: | Line 110: | ||
===== Open Issues ===== | ===== Open Issues ===== | ||
+ | |||
+ | |||
+ | ===== Discussion ===== | ||
+ | |||
+ | Regular type checks | ||
+ | |||
+ | During the discussion especially the idea of regular type checks instead of castings came up: | ||
+ | |||
+ | <code php> | ||
+ | $years = [" | ||
+ | [int $now, int $future] = $years; | ||
+ | </ | ||
+ | |||
+ | As a regular type check depends on the declare strict_types directive concerning the casting feature (strict_types=0 would result in an implicit cast similar to the proposed feature while strict_types=1 would result in a type error when the provided data doesn' | ||
===== Future Scope ===== | ===== Future Scope ===== | ||
Line 131: | Line 163: | ||
===== Patches and Tests ===== | ===== Patches and Tests ===== | ||
+ | |||
+ | The parser is already able to parse the syntax and requires no changes. The patch adds a change in the compile process in zend_compile_list_assign to be able to handle casting AST elements. | ||
https:// | https:// |
rfc/typecast_array_desctructuring.txt · Last modified: 2020/04/23 08:40 by wol-soft