Use a variable to define a PHP function

2019-01-05 04:01发布

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.

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.

1条回答
闹够了就滚
2楼-- · 2019-01-05 04:34

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:

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

查看更多
登录 后发表回答