Zbyszek Kisły
Zbyszek Kisły

Reputation: 2238

Passing function as an argument of another function in PHP

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

Answers (3)

Ja͢ck
Ja͢ck

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:

  1. a string comprising the function name to call,
  2. a closure (as above)
  3. an array comprising class (or instance) and method to call

Examples of the above is explained in the manual.

Update

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

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

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

hsz
hsz

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

Related Questions