Accept function as parameter in PHP
Just code it like this:
function example($anon) {
$anon();
}
example(function(){
// some codes here
});
it would be great if you could invent something like this (inspired by Laravel Illuminate):
Object::method("param_1", function($param){
$param->something();
});
Valid: (PHP 4 >= 4.0.1, PHP 5, PHP 7)
You can also use create_function to create a function as a variable and pass it around. Though, I like the feeling of anonymous functions better. Go zombat.
Update 09 - Jan - 2022
Warning
This function has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged.
Just to add to the others, you can pass a function name:
function someFunc($a)
{
echo $a;
}
function callFunc($name)
{
$name('funky!');
}
callFunc('someFunc');
This will work in PHP4.
It's possible if you are using PHP 5.3.0 or higher.
See Anonymous Functions in the manual.
In your case, you would define exampleMethod
like this:
function exampleMethod($anonFunc) {
//execute anonymous function
$anonFunc();
}