简体   繁体   English

PHP函数引用数组

[英]Array of reference to function in PHP

I would like to check value of integer and choose function depending on this. 我想检查整数值并据此选择函数。 I could do an if-elseif statement as following: 我可以执行以下if-elseif语句:

if($a==0) {function0($a);}
if($a==1) {function1($a);}

etc, but I would rather make an array of function, called maybe functionArray, which could be described as follows: 等等,但我宁愿制作一个函数数组,也许叫做functionArray,其描述如下:

$functionArray=array( function0($a), function1($a) );

etc, so that we execute function based on $a value, which belongs to $functionArray[$a] . 等等,因此我们基于$a值执行函数,该值属于$functionArray[$a] Is that possible? 那可能吗? There will be over 20 functions depending on $a value, thats why I want to make it easier and avoid big if-elseif block. 取决于$a值,将有20多个函数,这就是为什么我要使其更容易避免使用大的if-elseif块。

Do not name a variable after its type. 不要在变量类型后命名。 $functionArray is rather bad name for a variable, you could at least name it a collection, however, in my example I will name it just functions . $functionArray对于变量来说是个坏名字,您至少可以将其命名为一个集合,但是,在我的示例中,我将其命名为functions

function funcOne($a) {
    echo $a+1;
}

function funcTwo($a) {
    echo $a+2;
}

$functions = array(1 => 'funcOne', 2 => 'funcTwo');

$a = 2;

$functions[$a]($a);

This might not work below PHP 5.4 and you might need additional assignation eg $calledFunction = $functions[$a]; $calledFunction($a) 在PHP 5.4以下,这可能不起作用,并且您可能需要其他分配,例如$calledFunction = $functions[$a]; $calledFunction($a) $calledFunction = $functions[$a]; $calledFunction($a) . $calledFunction = $functions[$a]; $calledFunction($a) Anyway, it's possible, you just need to add them as strings if you are going to use named functions. 无论如何,如果要使用命名函数,只需将它们添加为字符串即可。

You also can use anonymous functions to achieve that as well 您也可以使用匿名函数来实现

$functions = array(1 => function($a) { echo $a+1; }, 2 => function($a) { echo $a+2;});

$a = 2;

$functions[$a]($a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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