I know the original question asked about PHP 4.3, but now it's a few years later, and I just wanted to uphold my preferred way of doing this in PHP 5.3 or later.
PHP 5.3+ now includes support for anonymous functions (closures) , so you can use some standard methods of functional programming, for example, in languages such as JavaScript and Ruby (with a few caveats). Rewriting the call_user_func example above in the “close style” will look like I think is more elegant:
$barber = function($type) { echo "You wanted a $type haircut, no problem\n"; }; $barber('mushroom'); $barber('shave');
Obviously, in this example you are not buying a lot - strength and flexibility come when you pass these anonymous functions to other functions (as in the original question). So you can do something like:
$barber_cost = function($quantity) { return $quantity * 15; }; $candy_shop_cost = function($quantity) { return $quantity * 4.50; // It Moonstruck chocolate, ok? }; function get_cost($cost_fn, $quantity) { return $cost_fn($quantity); } echo '3 haircuts cost $' . get_cost($barber_cost, 3) . "\n"; echo '6 candies cost $' . get_cost($candy_shop_cost, 6) . "\n";
This can be done with call_user_func, of course, but I find this syntax clearer, especially after namespaces and member variables are involved.
One caveat: I will be the first to admit that I don’t know exactly what is happening here, but you cannot always cause a closure contained in a member or static variable, and possibly in some other cases. But reassigning it to a local variable will allow it to be called. So, for example, this will give you an error message:
$some_value = \SomeNamespace\SomeClass::$closure($arg1, $arg2);
But this is a simple solution to the problem:
$the_closure = \SomeNamespace\SomeClass::$closure; $some_value = $the_closure($arg1, $arg2);