symfony/symfony — pull request #11965 by florianv (2014-09-20 03:10:15+00:00)
Title: [ExpressionLanguage] Added closures support

| Q | A
| ------------- | ---
| Bug fix? | no
| New feature? | yes
| BC breaks? | no
| Deprecations? | no
| Tests pass? | yes
| Fixed tickets | https://github.com/symfony/symfony/issues/11938
| License | MIT
| Doc PR |

This PR adds closures support to the `ExpressionLanguage` for both compiled and evaluated mode.

As @stof suggested in https://github.com/symfony/symfony/issues/11938, I added a new syntax to differentiate them from functions. The simplest syntax I could come up with is to prepend a `$` to a function name.

## Evaluation mode

In evaluation mode, you can pass the closure as a variable when evaluation the expression.

```php
// => '3'
echo $language->evaluate('$add(1, 2)', array(
'add' => function ($a, $b) {
return $a + $b;
}
));
```

## Compilation mode

When compiled, the closure expression is unchanged because it uses the same syntax than php variables.

```php
$hello = function () {
return 'hello';
};

$world = function () {
return 'world';
};

// => hello world
$language = new ExpressionLanguage();
eval(sprintf('echo %s;', $language->compile('$hello() ~ " " ~ $world()')));
```