0

So, some time ago I build a parser for jQuery Query Builder plugin, which parses the formula into PHP code that returns some calculation based on added parameters, it could range from return $a + $b; to something like

if($a == 'some_value' || $c == 'other_value') {
    return $something;
} else if($b == 'something' && $d == 'anything') {
    return $something_else;
} else {
    return $anything;
}

and it could be even more complex. The thing is that it creates this as a string, which I then passed to another function which returns a dynamic function created with create_function, but that constructor in PHP is deprecated as of version 7.2.0.

My problem now is that I need to be able to create anonymous function with dynamic number of parameters, and those parameters need to have dynamic variable names. Here is my previous code

protected function createFunction($formula, &$data)
{
    $args = '';

    foreach($data as $key => $value) {
        $args .= '$' . $key . ', ';
    }

    return create_function(substr($args, 0, strlen($args) - 2), $formula);
}

As you can see, the $formula is that dynamic PHP code I wrote above, and $data is an associative array (usually a row from database). Any ideas?

Edit: Forgot to mention, the formula itself is not the problem, as I can just use eval() function for that (I'm not concerned with security here so it's ok), it's just that I'm not sure how to add dynamic number of parameters with dynamic variable names.

1 Answer 1

1

You may go with Anonymous functions with this.

I had used eval in this case due to your comment :

Edit: Forgot to mention, the formula itself is not the problem, as I can just use eval() function for that (I'm not concerned with security here so it's ok)

class Foo
{
    public function createFunction($formula, $args)
    {
        $func = function ($args) use ($formula) {
            foreach ($args as $key => $val) {
                $$key = $val;
            }
            return eval($formula);
        };
        return $func($args);
    }
}

$foo = new Foo;

$foo->createFunction('echo $a + $b;', ['a' => 1, 'b' => 2]);

a live sample for your code https://3v4l.org/HrMKN

Sign up to request clarification or add additional context in comments.

3 Comments

This looks good, I will test it a bit later and then probably mark this one as the right answer. Thanks
let me know if there are any issues
Ok, I've checked this, and it's good except one line (actually, all is good, just for my case I need to change it), return $func($args); needs to return the function, not the result of it, so it should be return $func; But everything else is perfect, thanks again. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.