Reputation: 2238
I want to pass function (not the result) as an argument of another function. Let's say I have
function double_fn($fn)
and i want to run given function ($fn) two times. Is there such mechanism in PHP? I know you in python function is a kind of variable but is PHP similar?
@edit is there similar way to use methods?
function double_fn(parrot::sing())
Upvotes: 4
Views: 832
Reputation: 173582
Since 5.3 (note) you do this with closures quite naturally:
function double_fn(callable $fn)
{
$fn();
$fn();
}
double_fn(function() {
echo "hi";
});
(note) type hint only since 5.4
The callable type can be a few things:
Examples of the above is explained in the manual.
edit is there similar way to use methods?
function double_fn(parrot::sing())
Doing that will pass the result of parrot::sing()
into the function; to pass a "reference" to the static method you would need to use either:
double_fn('parrot::sing');
double_fn(['parrot', 'sing']);
Upvotes: 5
Reputation: 798754
It's... a bit different. Pass the function name as a string.
function foo()
{
echo "foobar\n";
}
function double_fn($fn)
{
$fn();
$fn();
}
double_fn('foo');
Upvotes: 3
Reputation: 152226
You can use anonymous functions introduced in PHP 5.3.0:
function double_fn($fn) {
$fn();
}
double_fn(function(){
// fonction body
});
or:
$myFn = function(){
// fonction body
};
double_fn($myFn);
Upvotes: 1