简体   繁体   中英

PHP eval and dependency injection

I am writing a web application, which I want to be be "scriptable" - meaning that I want users to be able to write little snippets of code to add additional functionality.

The script to be run, simply returns a boolean, indicating whether a condition has been met - however, the logic depends on interrogating objects in the main block - so I need a way of injecting the environment in which eval is being called - into the script being interpreted.

Putting security concerns aside for a moment, this is what I want to do.

/* script pseudo code */
if object1.date() - today() < SOME_CONSTANT 
    return true;
else
   if object2.field1 == 123 && oject1.date() > object2.field2
       return true;
   else
       return false;

/* Main block of code */
$obj1 = New path\to\Object1();
$obj2 = New Path\To\Object2();

$result = eval($script);

if $result
    doSomething();

My questions then is:

How do I inject the environment into a string that is to be eval'd, so that I may access the object in the expression being evaluated?

The global statement makes global variables available inside a function. So put:

global $var1, $var2, $var3, ...;

in your function that calls eval , where these are all the global variables that the snippets should be able to access.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM