Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing function as an argument of another function in PHP

Tags:

function

oop

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())
like image 359
zbyshekh Avatar asked Sep 11 '25 09:09

zbyshekh


2 Answers

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']);
like image 138
Ja͢ck Avatar answered Sep 13 '25 23:09

Ja͢ck


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');
like image 34
Ignacio Vazquez-Abrams Avatar answered Sep 14 '25 01:09

Ignacio Vazquez-Abrams