jaytaph / Transphpile

PHP 7 to PHP 5.6 Transpiler
BSD 3-Clause "New" or "Revised" License
177 stars 9 forks source link

Only evaluate right hand side of `??` if left value is null #18

Open TysonAndre opened 7 years ago

TysonAndre commented 7 years ago

It's possible to optimize the special cases. reset() wasn't used because that would emit a warning in php7 if non-references were used.

Motivation: if the right hand size can throw, then the transpiled code should only evaluate the right hand side if the left hand side is null. (E.g. foo($args) ?? bar($otherargs), bar may throw)

E.g. this converts $x = $y ?? 2 into the below expression (?: is the only operator which evaluates the left hand side once and conditionally evaluates the right hand side)

$x = \call_user_func(function ($v1) {
    return $v1[0];
}, \call_user_func(function ($v1) {
    return isset($v1) ? array($v1) : null;
}, @$y) ?: array(2));

EDIT: Forgot that should be call_user_func on the outside