Adam Pietrasiak
Adam Pietrasiak

Reputation: 13224

PHP: Create global function out of anonymous function

I want to create global function with dynamic name, but I dont want to write code of function as string, as it's required in PHP docs about create_function function.

Dream scenario would be like:

$functionName = "new_super_function";
$functionBody = function($a,$b) { return $a + $b; };

if ( !function_exists($functionName) ) create_function($functionName, $functionBody);

//from here my function with dynamic name is ready
//I could now call it like call_user_func($functionName, 5, 7) => 12
//or just use it later like new_super_function(5,7) => 12

I was looking for such sort of possibility but I couldnt find anything. Any ideas?

Upvotes: 1

Views: 67

Answers (2)

Furgas
Furgas

Reputation: 2844

I thought it would be fun to try to answer it. You would have to create your own create_function method.

function my_create_function($name, $callable) {
    $GLOBALS['my_functions'][$name] = $callable;

    $call_wrapper = sprintf('function %s() {
        $arguments = func_get_args();
        return call_user_func_array($GLOBALS["my_functions"][%s], $arguments);
    }', $name, $name);

    eval($call_wrapper);
}

Test:

class Test {
    static public function prepare() {
        $add_function = function($a, $b) { return $a + $b; };

        var_dump($add_function(1, 2));

        my_create_function('my_add', $add_function);
    }

    static public function testit() {
        var_dump(call_user_func('my_add', 1, 2));

        var_dump(call_user_func_array('my_add', array(1, 2)));

        var_dump(my_add(1, 2));
    }
}

Test::prepare();
Test::testit();

Upvotes: 0

Rizier123
Rizier123

Reputation: 59701

Just assign the function body to the function name like this:

$functionName = "new_super_function";
$functionBody = function($a,$b) { return $a + $b; };

if (!function_exists($functionName))
    $functionName = $functionBody;

echo call_user_func($functionName, 5, 7);  //Same as: echo $functionName(5, 7);

output:

12

EDIT:

If you want to declare an anonymous function which you can also call in other function, this won't be possible, since it is assigned to a variable and the variable is in a scope, so you either have to pass the variable with the anonymous function as argument or use the global keyword.

Upvotes: 3

Related Questions