1

In PHP there is a function called extract, which takes an array, and transforms your data into PHP variables. This function is very useful when I need to send variables to an include. Ex.

    extract(array( "test" => 123 ));
    require "test.php"

So test.php: print($test); Returns: 123

I need to do the same with functions (which I may not know). PHP 5.4 has support for use (Anonymous Function), which is quite interesting. Ex.

$test = 123;
call_user_func(function() use($test) {
    print($test);
});

However, I need to pass variables with other names and amounts. Something like:

$useArgs = array( "a" => 1, "b" => 2, "c" => 3 );
call_user_func(function() use(extract($useArgs)) {
    print($a);
    print($b);
    print($c);

    if(isset($d)) {
        print($d);
    }
});

How is this possible?

1 Answer 1

2

Just call extract() from inside your function

$useArgs = array( "a" => 1, "b" => 2, "c" => 3 );
call_user_func(function() use($useArgs) {
    extract($useArgs);
    print($a);
    print($b);
    print($c);

    if(isset($d)) {
        print($d);
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

Don't you still need to declare $useArgs as global?
No, why would you need that? Why would you use use if you also had to use global? The idea of use is to bind a global variable to your anonymous function's scope.
@kba +1. to be accurate, it binds a variable from the calling scope (global here is a bit ambiguous)

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.