On 12/09/2019 15:43, Robert Korulczyk wrote:
One additional line will make your code much more obvious and easier to read
and understand:
$i ??= 0;
$i++;
I don't find this code at all obvious:
foreach ( $something as $foo ) {
$i ??= 0;
$i++;
}
I mean, huh? What's that zero doing there, is it resetting the variable
every loop?
Now, in that simple case, you can and probably should initialise the
counter before the loop:
$i=0;
foreach ( $something as $foo ) {
$i++;
}
But that's not the example I gave earlier! The example I gave earlier
was a multi-dimensional array:
$foo = [];
foreach ( $something as $key1 ) {
foreach ( $somethingElse as $key2 ) {
$foo[$key1][$key2]++;
}
}
Even using ??= the initialise-everything-before-use version looks like this:
$foo = [];
foreach ( $something as $key1 ) {
foreach ( $somethingElse as $key2 ) {
$foo[$key1] ??= [];
$foo[$key1][$key2] ??= 0;
$foo[$key1][$key2]++;
}
}
Again, the values are confusing: the end result will never contain an
empty array at the first level, and will never contain a 0 at the second
level.
Those two lines aren't aiding the readability of that algorithm in any
way; I have to read past them to find the actual business of the loop,
which is counting something, using the ++ operator.
What's more, they're not preventing any bugs either! If I accidentally
reuse $foo from a previous loop, the extra lines won't reinitialise
anything for me; if I initialise it to empty, the two loops are
functionally identical.
So that's where I came up with two suggestions to actually add to the
language, rather than just taking away:
- a more granular way to express that this code is not actually
error-prone, combining the 3 lines back into one
- or, a way to express the intent of the code more clearly, such as
declaring the shape of an array
Regards,
--
Rowan Tommins (né Collins)
[IMSoP]
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php