Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

e.g.:

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

Is this possible? What's the best alternative?

share|improve this question
Are you coming from Javascript? – Chacha102 Sep 30 '09 at 18:28
Hahah yeah I am =] – Kirk Sep 30 '09 at 18:32

3 Answers

up vote 26 down vote accepted

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!');
share|improve this answer
Nice. +1 for completeness, and to give you the tenth vote. – karim79 Oct 3 '09 at 2:57
1  
I have reached enlightenment. Many thanks karim79 :) – Alex Barrett Oct 3 '09 at 3:34

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');
share|improve this answer

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();
share|improve this answer
1  
It brought me extreme pleasure to vote this down. There are all kinds of excellent reasons for first-class functions. – DaveGauer Oct 12 '12 at 23:11
Not going to downvote since it's already zero, but agreed... – Matt M. Apr 3 at 2:16

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.