Yekver
Yekver

Reputation: 5203

php anonymous functions in php 5

I've been using callback function like this:

private function make_f($arg1, $arg2)
{
    $callback =
        function ($my_var) use ($arg1, $arg2)
        {
            return $my_var  * $arg1 * arg2;
        };
    return $callback;
}

It supports by PHP 5.3.0 but my hosting provider has PHP 5.2.6 so it doesn't work. Is there any way to repair this somehow?

Upvotes: 2

Views: 214

Answers (1)

Ry-
Ry-

Reputation: 225291

That really depends on what $arg is. For any possible value of $arg, I can only come up with something like this:

public static $arguments = array();

private function make_f($arg)
{
    $variable_name = uniqid();

    ThisClass::$arguments[$variable_name] = $arg; // Replace ThisClass with the name of the actual class

    $callback = create_function('$my_var', 'return $my_var * ThisClass::$arguments[\'' . $variable_name . '\'];');

    return $callback;
}

Here's a demo.

Upvotes: 4

Related Questions