Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Variable in a function name

Tags:

variables

php

I want to trigger a function based on a variable.

function sound_dog() { return 'woof'; }
function sound_cow() { return 'moo'; }

$animal = 'cow';
print sound_{$animal}(); *

The * line is the line that's not correct.

I've done this before, but I can't find it. I'm aware of the potential security problems, etc.

Anyone? Many thanks.

like image 506
LibraryThingTim Avatar asked Nov 22 '09 04:11

LibraryThingTim


People also ask

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.

How do you call a method with a variable name?

There are two methods for doing this. One is directly calling function by variable name using bracket and parameters and the other is by using call_user_func() Function but in both method variable name is to be used. call_user_func( $var ); call_user_func( $var1 , "fun_function" );

What is a variable function in PHP?

Introduction. If name of a variable has parentheses (with or without parameters in it) in front of it, PHP parser tries to find a function whose name corresponds to value of the variable and executes it. Such a function is called variable function. This feature is useful in implementing callbacks, function tables etc.


2 Answers

You can do that, but not without interpolating the string first:

$animfunc = 'sound_' . $animal;
print $animfunc();

Or, skip the temporary variable with call_user_func():

call_user_func('sound_' . $animal);
like image 170
scribble Avatar answered Oct 02 '22 22:10

scribble


You can do it like this:

$animal = 'cow';
$sounder = "sound_$animal";
print ${sounder}();

However, a much better way would be to use an array:

$sounds = array('dog' => sound_dog, 'cow' => sound_cow);

$animal = 'cow';
print $sounds[$animal]();

One of the advantages of the array method is that when you come back to your code six months later and wonder "gee, where is this sound_cow function used?" you can answer that question with a simple text search instead of having to follow all the logic that creates variable function names on the fly.

like image 36
Greg Hewgill Avatar answered Oct 02 '22 23:10

Greg Hewgill