Twig
Twig copied to clipboard
Unexpected result using flashbag.get in a ternary operator.
Using flashbag.get in a ?: ternary operator doesn't work consistently with how PHP handles ternary operators. For example, {% set form_data = app.session.flashbag.get('form_data') ?: default_data %}, where form_data is populated, should return the contents of form_data, but it returns an empty array.
My assumption is that the if part of the condition is clearing the bag and the then part is calling flashbag.get a 2nd time and so returning the result of an empty flash bag.
PHP on the other hand stores and returns the result from the if condition, it does not execute the if condition twice.
For example:
function get() {
static $count = 0;
$count++;
return $count;
}
echo get() ?: false;
outputs 1 and not 2.
So it appears Twig's ternary operator is doing the equivalent of:
echo get() ? get() : false;