使用变量定义 PHP 函数 [英] Use a variable to define a PHP function
问题描述
我想使用变量动态命名一些函数,如下所示:
I'd like to dynamically name a few functions using variables, like this:
$thing = 'some_function';
function $thing() {
echo 'hi!';
}
我知道我可以使用这样的变量调用一个函数:
I know I can call a function using a variable like this:
$something = 'function_exists';
if( $something('print_r') ) {
echo 'Yep';
}
但上面的例子对我不起作用.
But the top example doesn't work for me.
有什么想法吗?
我正在使用具有模块的系统.每个模块都是一个单独的 php 脚本,可以在特定文件夹中添加或删除.
I'm using a system that has modules. Each module is a single php script that can be added or taken away from a specific folder.
每个模块都需要一个新函数来初始化它.我正在查找文件名,然后我想循环并创建一系列函数,每个模块一个.
Each module needs a new function to initialise it. I'm glob'ing for the file names, then I want to loop and create a series of functions, one for each module.
我使用的是现有系统,无法重写模块处理.
I'm using an existing system and can't rewrite the module handling.
另一种方法是将所有 init 函数写出并对其进行硬编码,但随着列表的增长,代码也会增加 - 如果模块被移除,则会引发错误.
The alternative would be to just write all the init functions out and hard code them, but as the list grows so does the code - and if a module is taken away errors are thrown.
推荐答案
你能做的是
$thing = 'some_function';
$$thing = function() {
echo 'hi';
};
$some_function();
在 php <5.3,你必须使用 create_function
而不是 匿名函数:
In php < 5.3, you'll have to use create_function
instead of the anonymous function:
// Use this in < 5.3
$thing = 'some_function';
$$thing = create_function('',
'echo "hi";'
);
$some_function();
话虽如此,用动态名称定义函数是一个坏主意.相反,创建一个你调用的函数数组,或者使用多态.
That being said, defining functions with dynamic names is a bad idea. Instead, create an array of functions you call in to, or use polymorphism.
这篇关于使用变量定义 PHP 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!