Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...