简体   繁体   中英

PHP: Variable in a function name

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.

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);

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.

http://php.net/manual/en/functions.variable-functions.php

To do your example, you'd do

$animal_function = "sound_$animal";
$animal_function();

You should ask yourself why you need to be doing this, perhaps you need to refactor your code to something like the following:

function animal_sound($type){ 
    $animals=array(); 
    $animals['dog'] = "woof"; 
    $animals['cow'] = "moo"; 
    return $animals[$type];
}

$animal = "cow";
print animal_sound($animal);

You can use $this-> and self:: for class-functions. Example provided below with a function input-parameter.

$var = 'some_class_function';
call_user_func(array($this, $var), $inputValue); 
// equivalent to: $this->some_class_function($inputValue);

You can use curly brackets to build your function name. Not sure of backwards compatibility, but at least PHP 7+ can do it.

Here is my code when using Carbon to add or subtract time based on user chosen type (of 'add' or 'sub'):

$type = $this->date->calculation_type; // 'add' or 'sub'

$result = $this->contactFields[$this->date->{'base_date_field'}]
                   ->{$type.'Years'}( $this->date->{'calculation_years'} )
                   ->{$type.'Months'}( $this->date->{'calculation_months'} )
                   ->{$type.'Weeks'}( $this->date->{'calculation_weeks'} )
                   ->{$type.'Days'}( $this->date->{'calculation_days'} );

The important part here is the {$type.'someString'} sections. This will generate the function name before executing it. So in the first case if the user has chosen 'add', {$type.'Years'} becomes addYears .

For PHP >= 7 you can use this way:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM