2

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?

5
  • I don't see where $my_var comes from. Commented Apr 17, 2012 at 22:59
  • That pretty much depends on what $arg is. Commented Apr 17, 2012 at 23:01
  • 2
    @Dan Lee: $my_var will be passed as a parameter when the closure is called in the future. Commented Apr 17, 2012 at 23:05
  • 1
    PHP 5.0 is seriously ancient (it was released in 2005). You should probably consider a better hosting provider. Commented Apr 17, 2012 at 23:07
  • 1
    @duskwuff My mistake, it's 5.2.6 Commented Apr 17, 2012 at 23:11

1 Answer 1

4

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.

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

2 Comments

@webbiedave: How so? I'm pretty sure uniqid doesn't depend solely on the clock. Or do you mean something else?
I deleted my comment after re-reading :) This solution works and is pretty much the only way to achieve this < 5.3. @Yekver: Just keep in mind that create_function will add a new function in memory everytime make_f is called (it won't reuse). So, if you're calling 100's of times in a loop, memory will be eaten. Other than that, this answers the OP's question perfectly. + 1

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.