1

I want to do something like this:

function func($callback) {
    $result = $callback(???);    // $callback must be called here
    //...
}

//...
func(function(['foo' => 'buu']) {
    $a = func_get_arg(0);

    // do something with $a and return something...    
    return $something;       
})

It is possible in php?

I can do something like below, but this is not what I want to do:

function func($args, $callback) {
    $result = $callback($args);
    //...
}

func(['foo' => 'boo'], function($args) {
     $a = $args; // etc.
})
4
  • It seems to me like ['foo' => 'boo'] is being set where the callback is set, so why not just assign $a to ['foo' => 'boo'] in the callback instead of trying to use func_get_arg(0);? Commented Oct 5, 2018 at 9:39
  • 1
    Does this help? stackoverflow.com/questions/52200682/… Commented Oct 5, 2018 at 9:51
  • @Davіd: You're right. But this is only stupid example. Commented Oct 5, 2018 at 9:57
  • @Barry. Thank You, this solved my problem :) Commented Oct 5, 2018 at 9:58

1 Answer 1

3

I use anonymous function this ways :

$mySuperFunction = function($arg)
{
    echo ("Hello " . $arg);
};

function AnotherFunction($args)
{
    echo ("Another hello " . $args);
}

function WrappingAnonymous($callback, $args)
{
    $callback($args);
}

function WrappingAnonymousWithoutArgs($callback)
{
    $callback();
}

WrappingAnonymous($mySuperFunction, "World");
WrappingAnonymous("AnotherFunction", "World");
WrappingAnonymous(function($someArgs)
{
    echo "Yet another Hello " . $someArgs;
}, "World");


WrappingAnonymousWithoutArgs(function($someArgs = "World")
{
    echo "Now, a 4th other Hello " . $someArgs;
});

Outputs :

Hello World

Another hello World

Yet another Hello World

Now, a 4th other Hello World

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

Comments

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.