Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 678
Mick Avatar asked Aug 27 '11 10:08

Mick


People also ask

How do you define a function in PHP?

PHP User Defined FunctionsA function is a block of statements that can be used repeatedly in a program. A function will not execute automatically when a page loads. A function will be executed by a call to the function.

How do you call a PHP function as a variable?

Use the Variable Method to Call a Function From a String Stored in a Variable in PHP. In PHP, we can also store the functions in variables. The function name should be assigned to a variable as a string, and then we can call the function a variable.

How can use variable in one function in another PHP?

You need to instantiate (create) $newVar outside of the function first. Then it will be view-able by your other function. You see, scope determines what objects can be seen other objects. If you create a variable within a function, it will only be usable from within that function.


1 Answers

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.

like image 175
phihag Avatar answered Oct 02 '22 20:10

phihag