[php-src] Issue #12800: Null Coalescing Operator + Ternary Operator Returns Wrong Result.
| From: | 3Descape | Date: | Mon, 27 Nov 2023 17:49:13 +0000 |
| Subject: | [php-src] Issue #12800: Null Coalescing Operator + Ternary Operator Returns Wrong Result. | ||
| Groups: | php.bugs | ||
| Request: | Send a blank email to php-bugs+get-245906@lists.php.net to get a copy of this message | ||
Issue: https://github.com/php/php-src/issues/12800
Author: 3Descape
### Description
The following code:
```php
<?php
$a = "A";
echo("Null Coalescing Operator: ");
echo($a ?? true ? "B" : "C");
echo("\nExpected result according to Documentation: ");
if(isset($a)) {
echo($a);
}
else {
echo(true ? "B" : "C");
}
```
Resulted in this output:
```
Null Coalescing Operator: B
Expected result according to Documentation: A
```
According to the equivalent code given in the
[documentation](https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce)
once whould expect the Null Coalescing Operator to return "A", since
$a is
set and not null. According to the equivalent code, the right hand side of the
?? operator (else branch in the equivalent code) should not be executed at all, when
$a exists.
The implementation of A ?? B currently seems to be equivalent to
isset(A) ? A : B
which, for A = $a and B = true ? "B" : "C", becomes
isset($a) ? $a : true ? "B" : "C"
which, [according to theleft-associativity prior to PHP
8.0.0](https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary)
is evaluated as
(isset($a) ? $a : true) ? "B" : "C" = "B".
Note: I also tested the null coalescing operator in php 8.2.10, I am just referecing php < 8.0
behaviour to speculate on the implementation problem.
Though, it should be
A ?? B = isset(A) ? A : (B)
which, for A = $a and B = true ? "B" : "C", becomes
isset($a) ? $a : (true ? "B" : "C)" = "A".
### PHP Version
8.2.10
### Operating System
_No response_