I wrote recently about some changes that I’d like to propose for list()
in core PHP for version 8.3: namely that it should work with iterables
as well with arrays, and that it should allow a variadic
“argument” that would assign all entries that were part of the original array being listed, but that weren’t explicitly assigned in the list.
Those weren’t the only changes that I would like to see implemented for list()
.
If we used list()
to extract entries that don’t exist in the array:
$data = [1 => 'A', 2 => 'B'];
[1 => $firstValue, 2 => $secondValue, 3 => $thirdValue] = $data;
var_dump($firstValue, $secondValue, $thirdValue);
then this will trigger a Notice in PHP 7, promoted to a Warning in PHP 8, and assign a null value to that variable. It becomes even more problematic if we’re assigning those extracted elements to class properties that aren’t nullable:
class Foo {
private int $firstValue;
private int $secondValue;
private int $thirdValue;
public function __construct(array $data = []) {
[$this->firstValue, $this->secondValue, $this->thirdValue] = $data;
}
}
$data = [1, 2];
$foo = new Foo($data);
We still get the Warning (or Notice), but this will also now result in a Fatal Uncaught TypeError because we’re trying to assign that null to the $thirdValue
property, which doesn’t allow nulls; making it a less than ideal situation.
So what can we do to prevent this?
Continue reading →