0

I'm trying to understand the popular use of PHP closure/ callback of functions in routing requests within modern frameworks. Slim for example, allows you to do the following:

$app->get('/hello/:name', function ($name) {
    echo "Hello, $name";
});
$app->run();

My experiment:

class Foo
{
    private $string;
    private $callback;

    public function get($string, $callback)
    {
        $this->string = $string;
        $this->callback = $callback;
    }

    public function run()
    {
        return $this->get($this->string, $this->callback);
    }
}

$Foo = new Foo;
$Foo->get('/world', function($name) {
    return "Hello " . $name;
});

$Foo->run();

How can execute the callback in the class so it return Hello World?

2 Answers 2

1

When designing frameworks it's a bit more complex in order to get better flexibility.
But on this simple case you simply could use call_user_func_array() or call_user_func(). I adivise to use call_user_func_array() because it's easier when passing many args:

class Foo
{
    private $string;
    private $callback;

    public function get($string, callable $callback)
    {
        $this->string = $string;
        $this->callback = $callback;
    }

    public function run()
    {
         return call_user_func_array($this->callback, [$this->string]);
        # OR 
        # return call_user_func($this->callback, $this->string);
        # OR
        #$fn = $this->callback; return $fn($this->string);

    }
}

$Foo = new Foo;
$Foo->get('/world', function($name) {
    return "Hello " . $name;
});

print $Foo->run();
Sign up to request clarification or add additional context in comments.

Comments

1

Based on your sample code, it should be like this:

    public function get($string, $callback)
    {
        //assign input parameter to object's propety
        $this->string = $string;
        $this->callback = $callback;

    }

    public function run()
    {
        /* if you want to avoid using this variable
           use call_user_func */
        $callback = $this->callback;

        // run the callback
        return $callback($this->string);
    }
}

$Foo = new Foo;
$Foo->get('world', function($name) {
    return "Hello " . $name;
});

$return = $Foo->run();
var_dump($return); //this will return 'Hello world'

2 Comments

Sorry, i didn't see @elipsmartins answer when posting -- its not yet there when i'm writing. Our answer actually same. I'm still new in Stackoverflow.
No worries. It helps too! ;)

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.