Pass a function by reference in PHP

Viewed 46342

Is it possible to pass functions by reference?

Something like this:

function call($func){
    $func();
}

function test(){
    echo "hello world!";
}

call(test);

I know that you could do 'test', but I don't really want that, as I need to pass the function by reference.

Is the only way to do so via anonymous functions?

Clarification: If you recall from C++, you could pass a function via pointers:

void call(void (*func)(void)){
    func();
}

Or in Python:

def call(func):
    func()

That's what i'm trying to accomplish.

11 Answers
function func1(){
    echo 'echo1 ';
    return 'return1';
}

function func2($func){
    echo 'echo2 ' . $func();
}

func2('func1');

Result:

echo1 echo2 return1

You can create a reference by assigning the function to a local variable when you declare it:

$test = function() {
    echo "hello world!";
};

function call($func){
    $func();
}

call($test);

As of PHP 8.1, you can use First-class callables:

call(test(...));

You can even use methods:

call($obj->test(...));

As simple as it is.

It appears a bit unclear why do you want to pass functions by reference? Usually things are passed by reference only when the referenced data needs to be (potentially) modified by the function.

As PHP uses arrays or strings to refer functions, you could just pass an array or a string by reference and that would allow the function reference to be modified.

For example, you could do something like

<?php
$mysort = function($a, b) { return ($a < $b) ? 1 : -1; };
adjust_sort_from_config($mysort); // modifies $mysort
do_something_with_data($mysort);

where

<?php
function load_my_configuration(&$fun)
{
  $sort_memory = new ...;
  ...
  $fun = [$sort_memory, "customSort"];
  // or simply
  $fun = function($a, b) { return (rand(1,10) < 4 ? 1 : -1; };
}

This works because there are three ways to refer to function in PHP via a variable:

  • $name – the string $name contains the name of the function in global namespace that should be called
  • array($object, $name) – refers to method called string $name of object $object.
  • array($class, $name) – refers to static function string $name of class $class.

If I remember correctly, the methods and static functions pointed by these constructs must be public. The "First-class callable syntax" should improve this restriction given recent enough PHP version but it seems to be just some syntactic sugar around Closure::fromCallable().

Anonymous functions work the same behind the scenes. You just don't see the literal random names of those functions anywhere but the reference to an anonymous function is just a value of a variable, too.

Related