Coder Perfect

In PHP, accept a function as a parameter.

Problem

I’ve been wondering whether it’s feasible to pass a function as a parameter in PHP; I’m looking for something similar to what you’d see in JS:

object.exampleMethod(function(){
    // some stuff to execute
});

I’d like to call that function from within exampleMethod. Is that something PHP can do?

Asked by Cristian

Solution #1

If you’re using PHP 5.3.0 or higher, it’s doable.

In the documentation, look up Anonymous Functions.

In your situation, exampleMethod would be defined as follows:

function exampleMethod($anonFunc) {
    //execute anonymous function
    $anonFunc();
}

Answered by zombat

Solution #2

You can also supply a function name to add to the others:

function someFunc($a)
{
    echo $a;
}

function callFunc($name)
{
    $name('funky!');
}

callFunc('someFunc');

This is compatible with PHP 4.

Answered by webbiedave

Solution #3

PHP 4 >= 4.0.1, PHP 5, PHP 7 are all valid.

You can also build a function as a variable and pass it around with create function. However, I prefer the feel of anonymous functions. Zombat, zombat, zombat, zombat,

Updated on January 9, 2022

As of PHP 7.2.0, this function is DEPRECATED, and as of PHP 8.0.0, it has been REMOVED. It is strongly advised against relying on this function.

Answered by Jage

Solution #4

Just code it like this:

function example($anon) {
  $anon();
}

example(function(){
  // some codes here
});

It’d be fantastic if you could come up with something similar to this (influenced by Laravel Illuminate):

Object::method("param_1", function($param){
  $param->something();
});

Answered by Saint Night

Solution #5

It’s better to validate the Anonymous Functions first, according to @zombat’s response:

function exampleMethod($anonFunc) {
    //execute anonymous function
    if (is_callable($anonFunc)) {
        $anonFunc();
    }
}

Since PHP 5.4.0, you may also validate the argument type:

function exampleMethod(callable $anonFunc) {}

Answered by Nick Tsai

Post is based on https://stackoverflow.com/questions/2700433/accept-function-as-parameter-in-php