views:

192

answers:

3

e.g.:

$functions = array(
  'function1' => function($echo) { echo $echo; }
);

Is this possible? What's the best alternative?

+10  A: 

There are a few options. Use create_function:

$functions = array(
  'function1' => create_function('$echo', 'echo $echo;')
);

Simply store the function's name as a string (this is effectively all create_function is doing):

function do_echo($echo) {
    echo $echo;
}

$functions = array(
  'function1' => 'do_echo'
);

If you are using PHP 5.3 you can make use of anonymous functions:

$functions = array(
  'function1' => function($echo) {
        echo $echo;
   }
);

All of these methods are listed in the documentation under the callback psuedo-type. Whichever you choose, the recommended way of calling your function would be with either the call_user_func or call_user_func_array function.

call_user_func($functions['function1'], 'Hello world!');
Alex Barrett
Nice. +1 for completeness, and to give you the tenth vote.
karim79
I have reached enlightenment. Many thanks karim79 :)
Alex Barrett
A: 

To follow up on Alex Barrett's post, create_function() returns a string that you can actually use to call the function, thusly:

$function = create_function('$echo', 'echo $echo;' );
$function('hello world');
RibaldEddie
+1  A: 

A better answer might be a question as to why you are putting functions in arrays. Depending on what you're trying to accomplish, this may not be the best use of your code.

edit:

here's a good way to declare and use php functions:

(at the top of the page)

function name(){
}

(in your code)

name();

:)

Nice and clean. If you need something more structured than that, you should really look into objects.

$object->function();
Citizen