Ulad Kasach
Ulad Kasach

Reputation: 12828

Store functions as elements of an array php

Is it possible store a few functions in an array by reference or by anonymous function?

For example:

 $array = [fun1, function(){ /*do something*/ }, fun3];

where fun1 and fun3 are defined as

 function fun1(){/*do something*/}

Upvotes: 1

Views: 1998

Answers (3)

Darren
Darren

Reputation: 13128

As long as your PHP version is >= 5.3 you'll be able to harness anonymous functions and regular functions in your array:

function yourFunction($string){
    echo $string . " : by reference";
};

$array = array(
    'a' => function($string){
        echo $string;
    },
    'b' => 'yourFunction',
);

You can use the call_user_func or call_user_func_array functions.

call_user_func($array['a'], 'I love things');
call_user_func($array['b'], 'I love things');

Or As @Andrew stated in the comments too, you could call it as the following:

$array['a']('I love things');
$array['b']('I love things');

If you'd like to read more about these callback methods, it's filed under the callback pseudo-type documentation on PHP.net and it is well worth a read!

Upvotes: 4

Jorge Hess
Jorge Hess

Reputation: 550

Here is an example, with anonymous function and by reference

 $test = array();

 $test['testFunction'] = function($message) {
  echo $message;
 };


 function show_msg($message) {
     echo $message;
 }

 $test['testFunction2'] = 'show_msg';

 call_user_func($test['testFunction'], 'Hi!');

 call_user_func($test['testFunction2'], 'Hello world!');
?>

Upvotes: 1

deceze
deceze

Reputation: 522145

Yes, you can do that, however you can't store the function as literal, but instead you have to refer to it by its name:

$array = ['fun1', function () { /*do something*/ }, 'fun3'];

foreach ($array as $fun) {
    $fun();
}

Note that because it's by name, you'll have to use the fully qualified name should your function happen to be in a namespace; e.g. 'foo\bar\baz'.

Upvotes: 2

Related Questions