Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: define functions with variable names

Tags:

php

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

like image 640
julien_c Avatar asked Feb 03 '23 14:02

julien_c


1 Answers

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.

like image 89
mario Avatar answered Feb 05 '23 04:02

mario