Store and execute PHP code snippets using Evalue class.
- store PHP code for multiple executions;
- provide context variables during construction and execution;
- support for complex PHP code snippets;
- automatic stripping of
<?phptags; - variable scope isolation between runs;
composer require maximaster/evalueuse Maximaster\Evalue\Evalue;
// Create an Evalue instance with PHP code
$evalue = new Evalue('return $number * 2;');
// Run the code with context
$result = $evalue->run(['number' => 21]); // Returns 42$evalue = new Evalue(
'return $greeting . " " . $name;',
['greeting' => 'Hello']
);
// Run with additional context
$result = $evalue->run(['name' => 'John']); // Returns "Hello John"// Multi-line code
$code = <<<'PHP'
$sum = 0;
for($i = 1; $i <= $max; $i++) {
$sum += $i;
}
return $sum;
PHP;
$evalue = new Evalue($code);
$result = $evalue->run(['max' => 5]); // Returns 15$evalue = new Evalue(
'return $name;',
['name' => 'John']
);
// Constructor context can be overridden in run()
$result = $evalue->run(['name' => 'Jane']); // Returns "Jane"eval() function. Only use it with trusted code. Never execute user-provided
code without proper validation and sanitization.
Variable names in the context must follow PHP's variable naming conventions:
- Must start with a letter or underscore
- Can contain letters, numbers, underscores
- Supports extended ASCII characters (e.g.,
π,área,über)
Invalid examples:
$evalue->run([
'123name' => 'invalid', // Invalid: starts with number
'my-var' => 'invalid', // Invalid: contains hyphen
'my var' => 'invalid' // Invalid: contains space
]);composer test # runs kahlan tests.
composer lint # runs static analysis to check the code.
composer ci # both test & lint.
composer fix # automatically fixes some lint errors.