Question

I am interested in something google couldn't really help me with...

I know that its possible to use anonymous functions and also store functions in a variable in PHP like that

$function = function myFoo() { echo "bar"; }

and call it using the variable: $function();

So far so good but what if I have a function or method declared somewhere but not saved on intializing?

I have a function that shall expect a callable, of course call_user_func() can help me here but then I need to pass the method name in my callback handler which I think is pretty unsafe because in the moment I add the callback I cant say if it really is a function and exists when I store it.

Thatswhy I would like to realize the following szenario:

This function:

function anyFunction() {
    echo "doWhatever...!";
}

should be saved in a variable at a later point in time:

$myOtherFunction = get_registered_func("anyFunction"); 

I know get_registered_func() doesnt exist but I want to know if this is possible somehow!

With this I could now have another function

function setCallback(callable $theCallbackFunction) { }

And use it like this:

setCallback($myOtherFunction);

This would have a great advantage that an exception / a fatal is thrown when the parameter is no function or does not exist.

So in short, is there a way to store a previously defined, already existing function or method in a variable?

Was it helpful?

Solution

PHP's callable meta type can be:

  • a string
  • an array
  • an anonymous function

Only the latter one is somewhat "type safe", i.e. if you get an anonymous function you know it's something you can call. The other two options are merely formalised informal standards (if that makes sense) which are supported by a few functions that accept callbacks; they're not actually a type in PHP's type system. Therefore there's basically no guarantee you can make about them.

You can only work around this by checking whether the callable you got is, well, callable using is_callable before you execute them. You could wrap this into your own class, for example, to actually create a real callable type.

OTHER TIPS

I see no reason why this shouldn't be possible, other than there not being a PHP function to do it. The anonymous function syntax is newly introduced in PHP, I wouldn'be surprised if it was still a little rough around the edges.

You can always wrap it:

function wrap_function ($callback) {
    if (is_callable($callback) === false) {
        throw new Exception("nope");
    }
    return function () {
        call_user_func($callback, func_get_args());
    }
}
$foo = new Foo();
$ref = wrap_function(array($foo, "bar"));

Not a good way, but maybe this helps you:

function foo($a) {
    echo $a;
}

$callFoo = 'foo';

$callFoo('Hello World!'); // prints Hello
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top