PHP code example of naotake51 / evaluation

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

    

naotake51 / evaluation example snippets


use Naotake51\Evaluation\Evaluation;

$evaluation = new Evaluation([
    'square' => function (array $arguments) {
        return $arguments[0] * $arguments[0];
    }
]);
$result = $evaluation('square(2) + square(2)'); // => 8

$evaluation = new Evaluation([
    '__add' => function (array $arguments) {
        return "$arguments[0] + $arguments[1]";
    }
]);
$result = $evaluation('1 + 2'); // => '1 + 2'

$evaluation = new Evaluation([
    '*' => function (string $identify, array $arguments) {
        return 'call' . $identify . '(' . implode(', ', $arguments). ')';
    }
]);
$result = $evaluation('hoge(1, 2)'); // => 'call hoge(1, 2)'

$evaluation = new Evaluation([
    'repeat' => [
        'string, integer|null' => function (string $str, ?int $repeat) {
            return str_repeat($str, $repeat ?? 2);
        },
    ]
]);
$result = $evaluation("repeat('abc', 3)"); // => 'abcabcabc'

$evaluation = new Evaluation([
    '__add' => [
        'string, string' => function (string $a, string $b) {
            return $a . $b;
        },
        'numeric, numeric' => function ($a, $b) {
            return $a + $b;
        },
    ]
]);
$result = $evaluation("'abc' + 'def'"); // => 'abcdef'

use Naotake51\Evaluation\Evaluation;
use Naotake51\Evaluation\Errors\EvaluationError;

try {
    $evaluation = new Evaluation([
        'hoge' => function (array $arguments) {
            return 'hoge';
        },
    ]);
    $result = $evaluation("fuga()"); // => UndefineFunctionError
} catch (EvaluationError $e) {
    error_log($e->getMessage()); // => 'function fuga is not exists.'
}