PHP code example of xylemical / php-expressions

1. Go to this page and download the library: Download xylemical/php-expressions 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/ */

    

xylemical / php-expressions example snippets




use Xylemical\Expressions\Math\BcMath;
use Xylemical\Expressions\Context;
use Xylemical\Expressions\ExpressionFactory;
use Xylemical\Expressions\Evaluator;
use Xylemical\Expressions\Lexer;
use Xylemical\Expressions\Parser;

$math = new BcMath();
$factory = new ExpressionFactory($math);
$lexer = new Lexer($factory);
$parser = new Parser($lexer);
$evaluator = new Evaluator();
$context = new Context();

$tokens = $parser->parse('1 + 1');
$result = $evaluator->evaluate($tokens, $context);

use Xylemical\Expressions\Token;
use Xylemical\Expressions\Value;

$factory->addOperator(new Value('\$[a-zA-Z_][a-zA-Z0-9_]*', function(array $operands, Context $context, Token $token) {
    return $context->getVariable(substr($token->getValue(), 1));
}));

$context->setVariable('example', 10);

$tokens = $parser->parse('2 * $example');
$result = $evaluator->evaluate($tokens, $context);

use Xylemical\Expressions\Token;
use Xylemical\Expressions\Procedure;

$factory->addOperator(new Procedure('ABS', 1, function(array $operands, Context $context, Token $token) {
    $value = $token->getValue();
    if (substr($value, 0, 1) === '-') {
        return substr($value, 1);
    }
    return $value;
}));

$tokens = $parser->parse('abs(-1.2)');
$result = $evaluator->evaluate($tokens, $context);