PHP code example of okvpn / expression-language
1. Go to this page and download the library: Download okvpn/expression-language library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
okvpn / expression-language example snippets
$lang = new TwigLanguage(options: ['cache' => __DIR__ . '/var/cache/twig']);
$context = ['var1' => 10, 'users' => [1, 2, 5], 'user' => 1];
$lang->evaluate('user in users ? users|length + 1 : var1')
$lang = new TwigLanguage();
$script = <<<TXT
...
{% return 10 + 15 %}
TXT;
var_dump($lang->execute($script, $context));
// execute with template
$loader = new \Twig\Loader\FilesystemLoader(__DIR__ . '/scripts');
$lang = new TwigLanguage(loader: $loader);
var_dump($lang->execute('test22.twig', $context));
$lang = new TwigLanguage(options: [
'cache' => __DIR__ . '/var/cache/twig',
'auto_reload' => true,
]);
$expr = 'user == 1 ? var1 + var2 : var1 + 1';
$lang->evaluate($expr, $context);
// Symfony EL
$sf = new ExpressionLanguage();
$expression = $sf->parse($expr, array_keys($context));
$sf->evaluate($expression, $context);
// Native PHP
$fn = static function ($context) {
return $context['user'] === 1 ? $context['var1'] + $context['var2'] : $context['var1'] + 1;
};
$t1 = microtime(true);
for ($i = 0; $i < 200000; $i++) {
// comment line where needed
$result = $fn($context);
$result = $sf->evaluate($expression, $context);
$result = $lang->evaluate($expr, $context);
}
echo (microtime(true) - $t1)/200000 * 1000000 . "\n";