maximaster / evalue
Eval as class.
1.0.0
2025-04-17 10:59 UTC
Requires
- php: >=8.1
Requires (Dev)
- kahlan/kahlan: ^6.0
- phpstan/phpstan: ^2.1
- symplify/easy-coding-standard: ^12.5
README
Store and execute PHP code snippets using Evalue class.
Features
- store PHP code for multiple executions;
- provide context variables during construction and execution;
- support for complex PHP code snippets;
- automatic stripping of
<?php
tags; - variable scope isolation between runs;
Installation
composer require maximaster/evalue
Usage
Basic Usage
use 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
With Constructor Context
$evalue = new Evalue( 'return $greeting . " " . $name;', ['greeting' => 'Hello'] ); // Run with additional context $result = $evalue->run(['name' => 'John']); // Returns "Hello John"
Complex Code Examples
// 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
Context Overriding
$evalue = new Evalue( 'return $name;', ['name' => 'John'] ); // Constructor context can be overridden in run() $result = $evalue->run(['name' => 'Jane']); // Returns "Jane"
Security
⚠️ Warning: This library uses PHP's eval()
function. Only use it with trusted code. Never execute user-provided
code without proper validation and sanitization.
Context Rules
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 ]);
Development / Contribution
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.