PHP:使用变量名定义函数 [英] PHP: define functions with variable names

查看:206
本文介绍了PHP:使用变量名定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组,我想定义名称为这些字符串的函数.有没有办法在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");

如何以编程方式定义xxx()yyy()zzz()?

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

非常感谢

推荐答案

如果确实需要,可以在 eval 阻止:

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.

这篇关于PHP:使用变量名定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆