开发者

PHP: define functions with variable names

开发者 https://www.devze.com 2023-04-03 13:21 出处:网络
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?

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");

H开发者_如何学Pythonow do I programmatically define xxx(), yyy(), and zzz()?

Many thanks


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.


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.


$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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号