Re: Undefined variables and the array append operator
| From: | Larry Garfield | Date: | Wed, 30 Mar 2022 14:26:50 +0000 |
| Subject: | Re: Undefined variables and the array append operator | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-117458@lists.php.net to get a copy of this message | ||
On Wed, Mar 30, 2022, at 9:11 AM, Claude Pache wrote:
>> Le 29 mars 2022 à 21:44, Rowan Tommins <rowan.collins@gmail.com> a écrit :
>>
>> Hi all,
>>
>> If $foo is not defined, statements such as $foo += 1 and $foo .= 'blah' raise
>> "undefined variable" Warnings in PHP 8, and will throw Errors in PHP 9. However, the very
>> similar looking $foo[] = 1 succeeds silently.
>>
>> This seems odd to me, as "append to string" and "append to array" seem
>> like very similar operations, with most of the same use cases and possible bugs.
>>
>>
>
>
> Hi,
>
> There are various subcases to consider:
>
> (1) $x[] = 42; and $x['y'] = 42; where $x is undefined
>
> (2) $x[] = 42; and $x['y'] = 42; where $x is null
>
> (3) $x['y'][] = 42; and $x['y']['w'] = 42; where $x is an
> array, and
> $x['y'] is undefined.
>
> Of course, I agree that (1) should be an error.
>
> The case (3) is similar to (1), but I think it is more controversial to
> change. I bet that they are various places in my code that take
> advantage of that feature, although personally I don’t mind to write
> $x['y'] ??= [ ]; when needed.
We should probably also consider if there are other places where we're comfortable with ??=
working correctly. I'm not sure off hand if it should be acceptable in 1 or 2, but it's a
question we should think through and document decisions on.
--Larry Garfield