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

julien_c
  • 4,942
  • 5
  • 39
  • 54
  • lets say you did define these strings as functions, what will you do with them? – TheTechGuy Sep 07 '11 at 17:20
  • They're hooks in a CMS. I want my plugin to do the exact same thing on every hook. – julien_c Sep 07 '11 at 17:24
  • Would anonymous functions be more useful to you? http://php.net/manual/en/functions.anonymous.php. – WayneC Sep 07 '11 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. – TheTechGuy Sep 07 '11 at 17:28
  • @SavageGarden No, I want to define them, not call them – julien_c Sep 07 '11 at 17:31
  • Possible duplicate of [Use a variable to define a PHP function](http://stackoverflow.com/questions/7213825/use-a-variable-to-define-a-php-function) – T.Todua Sep 01 '16 at 14:38

3 Answers3

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.

mario
  • 144,265
  • 20
  • 237
  • 291
  • Since it's for a strictly-development-only helper module, performance's not an issue, so I guess I'll use this approach. Thanks! – julien_c Sep 07 '11 at 17:34
  • Actually, I'll end up generating my PHP file from another PHP script, that will be cleaner. And it's so meta! :) – julien_c Sep 07 '11 at 17:47
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.

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • Ok, thanks. Do you have more info on this magic method trick? – julien_c Sep 07 '11 at 17:26
  • I'm not sure this would work in my case (hooks definition in a CMS). Will try it though, thanks. – julien_c Sep 07 '11 at 17:37
  • @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? – rineez Aug 17 '17 at 10:58
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.

Pheonix
  • 6,049
  • 6
  • 30
  • 48