rfc:typecast_array_desctructuring

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revisionBoth sides next revision
rfc:typecast_array_desctructuring [2020/04/07 09:49] – Add target version wol-softrfc: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:
 +
 +<code>
 +1,Test,2002
 +2,Example,2010
 +3,Demo,2016
 +</code>
 +
 +<code php>
 +$handle = fopen('test.csv', 'r');
 +while (($data = fgetcsv($handle)) !== false) {
 +    [(int) $id, (string) $data, (int) $year] = $data;
 +    // ...
 +}
 +</code>
  
 ===== 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 = ["2020", "2021"];
 +[int $now, int $future] = $years;
 +</code>
 +
 +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't match the type check) a regular type check covers different use cases than the proposed casting feature. (Also see future scopes)
  
 ===== 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://github.com/php/php-src/pull/5296 https://github.com/php/php-src/pull/5296
rfc/typecast_array_desctructuring.txt · Last modified: 2020/04/23 08:40 by wol-soft