[php-src] Issue #8520: Array key evaluation on a null type
| From: | mytuny | Date: | Mon, 09 May 2022 12:18:56 +0000 |
| Subject: | [php-src] Issue #8520: Array key evaluation on a null type | ||
| Groups: | php.bugs | ||
| Request: | Send a blank email to php-bugs+get-241442@lists.php.net to get a copy of this message | ||
Issue: https://github.com/php/php-src/issues/8520
Author: mytuny
### Description
When trying to retrieve an array item on a
null variable using the syntax
null['key'], the key evaluation mechanism still considered. Although this
seem to be trivial, such behavior is not expected when used in conjunction with the null-coalescing
operator ??.
Let's consider the following code:
```php
<?php
var_dump(null['key'] ?? 'default');
```
Resulted in this output:
```
default
```
Up to here nothing is clear about whether key evaluation got fired or not.
To determine that, we can delegate the key value evaluation to a dynamic function and, also,
let's throw an exception from within it to emphasize the behavior clearly:
```php
<?php
function evalKey() {throw new Exception();}
var_dump(null[evalKey()] ?? 'default');
```
Now, in the context of using the null-coalescing operator one can expect this to lead to the
right-hand-side of the operator being outputted without concerns about key evaluation since the
evaluated array of the left-hand-side is null at the first place and that's by
definition the role of the ?? operator (to test against null &
non-existent values)!
However, in this scenario the exception is ultimately thrown, which mean that the key is still being
evaluated even when the array is null:
```
Fatal error: Uncaught Exception ...
```
Now, it seem we have a competing concerns between array's key evaluation and null coalescing
evaluation which lead to some confusing about the expected behavior in such case!!
### PHP Version
PHP 8.1.0
### Operating System
_No response_