9

I have an array of strings and I want to define functions with names being these strings. Is there a way to do that in PHP?

$a = array("xxx", "yyy", "zzz");

How do I programmatically define xxx(), yyy(), and zzz()?

Many thanks

6
  • lets say you did define these strings as functions, what will you do with them? Commented Sep 7, 2011 at 17:20
  • They're hooks in a CMS. I want my plugin to do the exact same thing on every hook. Commented Sep 7, 2011 at 17:24
  • Would anonymous functions be more useful to you? php.net/manual/en/functions.anonymous.php. Commented Sep 7, 2011 at 17:27
  • that means you just want to declare them as function without a definition (already defined in this case). If that is the case, you dont need to declare them. Just call them be appending () with each string and possible parameters. Commented Sep 7, 2011 at 17:28
  • @SavageGarden No, I want to define them, not call them Commented Sep 7, 2011 at 17:31

3 Answers 3

9

If you really had to you could declare the function within an eval block:

foreach ($a as $functionname)
eval('
        function '.$functionname.' () {
            print 123;
        }
');

But that incurs some extra parsing time speed penalty over just declaring the functions in a file.

Sign up to request clarification or add additional context in comments.

2 Comments

Since it's for a strictly-development-only helper module, performance's not an issue, so I guess I'll use this approach. Thanks!
Actually, I'll end up generating my PHP file from another PHP script, that will be cleaner. And it's so meta! :)
2

You don't, it's not possible.

With a magic method trick you can achieve this on an instance object (so $obj->xxx() works, see: __call) but you cannot create a global function based on a variable name.

Note: I am aware that you can $var(), but that's not what the OP asked.

3 Comments

Ok, thanks. Do you have more info on this magic method trick?
I'm not sure this would work in my case (hooks definition in a CMS). Will try it though, thanks.
@julien_c Let me guess! You probably asked this question while you were working with Drupal update hooks? It's a mess. How did you solve it finally?
1
$a = array("xxx", "yyy", "zzz");

foreach($a as $functionname){
$code = <<< end
function $functionname(){
//your logic here for each function
}
end;
eval($code);
}

However please not that Eval is not advisable to be used, you should find some other approach.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.