Trondro Mulligan
Trondro Mulligan

Reputation: 505

Is it a bad practice to store function names in variables and call the function using the variable?

I'm currently using this technique:

$func = "filter_var";

if ($func('[email protected]', FILTER_VALIDATE_EMAIL)) {
    // do something
}

It works for me. It is very useful if I ever decide to rename my own functions. But I wonder if it's a bad practice or if there's any downside to using this?

Upvotes: 0

Views: 93

Answers (1)

Carcigenicate
Carcigenicate

Reputation: 45745

No, there's nothing wrong with this in general.

This can be extremely useful if you're using a function with a long name many times in an equation. It neatens things up quickly. It's also useful if you need to decide which function you want to use. You can use a ternary to pick between 2 functions, and store the chosen one in the variable for later.

This is also useful if you need a local function. Instead of polluting the namespace with a function that will never be used anywhere else, you can create a local anonymous function, and bind it to a variable locally.

Just be careful that you don't go overboard with it. "Renaming" functions constantly may be confusing to readers if the functions are being renamed without proper justification. You don't want your readers to have to constantly look up the page to see what names are shortcuts to what functions.

In your example, I wouldn't really say that it's justified, but it's a small example.

Upvotes: 1

Related Questions