Zend certified PHP/Magento developer

Splitting array into “list” and “dict”

Expressing intent is important to achieve readable and clear code. Unfortunately, PHP’s array is the very anti-thesis to this, as it can mean anything and nothing. One solution would be to split the array type-hint into list and dict, where an error would be thrown if an array with string keys where used as a list.

This could be implemented fairly easy in the PHP source code, marking an array as a list at creation:

$arr = []; 

but mark it as dict as soon as it is “abused”:

$arr['foo'] = 'bar'; 

or

$arr[345] = 'foo'; // In an array with only 3 elements 

There are of course more edge cases, but the point is to have a single boolean check, not to traverse the keys of the array, to decide if it’s a list or a dict.

It’s unfortunate that list is already used as a language construct to unpack an array. Otherwise, it could perhaps be used as an internal data structure together with dict, as in

$list = new List(); $list[] = 'first_element'; 

and

$dict = new Dict(); $dict['key'] = 'value'; 

(Yes, of course it’s possible to create these classes, but they would not have optimized data-structures in the PHP source-code, e.g. implementing the list as a dynamic array where read-access is constant and memory footprint small.)

Anyone knows an RFC or similar? Has this been proposed before?

Edit: Hacklang already did it: https://docs.hhvm.com/hack/built-in-types/arrays

Edit 2: And a PHP extension for PHP 7: https://www.php.net/manual/en/book.ds.php

Edit 3: And of course SPL: https://www.php.net/manual/en/spl.datastructures.php

Edit 4: This can be made backwards compatible. Maybe a better title would have been: “Add type-hints for list and dict“.

submitted by /u/usernameqwerty003
[link] [comments]