简体   繁体   English

使用变量来定义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. 但最好的例子对我不起作用。

Any ideas? 有任何想法吗?

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. 每个模块都是一个php脚本,可以添加或从特定文件夹中删除。

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. 我正在使用现有系统,无法重写模块处理。

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. 另一种方法是将所有init函数写出来并对其进行硬编码,但随着列表的增长,代码也会增长 - 如果模块被删除,则会抛出错误。

What you can do is 你能做的是

$thing = 'some_function';
$$thing = function() {
   echo 'hi';
};
$some_function();

In php < 5.3, you'll have to use create_function instead of the anonymous function : 在php <5.3中,你将不得不使用create_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. 相反,创建一个您调用的函数数组,或使用多态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM