PHP:函数名中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1777820/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:48:56  来源:igfitidea点击:

PHP: Variable in a function name

phpvariables

提问by LibraryThingTim

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.

任何人?非常感谢。

回答by scribble

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()跳过临时变量:

call_user_func('sound_' . $animal);

回答by Greg Hewgill

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_cowfunction 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.

数组方法的优点之一是,当您在六个月后回到您的代码并想知道“哎呀,这个sound_cow函数在哪里使用的?” 您可以通过简单的文本搜索来回答这个问题,而不必遵循动态创建变量函数名称的所有逻辑。

回答by Brendan Long

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

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

To do your example, you'd do

做你的例子,你会做

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

回答by Sam152

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

回答by parker_codes

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

您可以使用大括号来构建函数名称。不确定向后兼容性,但至少 PHP 7+ 可以做到。

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

这是我使用 Carbon 根据用户选择的类型(“add”或“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.

这里的重要部分是{$type.'someString'}部分。这将在执行之前生成函数名称。因此,在第一种情况下,如果用户选择了“添加”,则{$type.'Years'}变为addYears

回答by Nabi K.A.Z.

For PHP >= 7you can use this way:

因为PHP >= 7您可以使用这种方式:

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

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

回答by user1207013

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

您可以将$this->self::用于类函数。下面提供了带有函数输入参数的示例。

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