参考Array对PHP函数 [英] Array of reference to function in PHP

查看:107
本文介绍了参考Array对PHP函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查整数值,并根据该选择的功能。我可以做一个if elseif的声明如下:

I would like to check value of integer and choose function depending on this. I could do an if-elseif statement as following:

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

等等,但我宁愿做功能阵列,被称为也许functionArray,它可以描述如下:

etc, but I would rather make an array of function, called maybe functionArray, which could be described as follows:

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

等,让大家根据 $ A 价值,属于 $ functionArray [$一] 。那可能吗?会有依赖于 $ A 值超过20的功能,这就是为什么我要使它更容易和避免大的IF-ELSEIF块。

etc, so that we execute function based on $a value, which belongs to $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.

推荐答案

不要将其命名它的类型后的变量。 $ functionArray 是相当不好的名字为变量,你至少可以将其命名为一个集合,但是,在我的例子,我将它命名为刚功能

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.

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

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

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

$a = 2;

$functions[$a]($a);

这可能不起作用低于5.4 PHP,你可能需要额外的分配例如 $ calledFunction = $函数[$一]; $ calledFunction($ A)。无论如何,这是可能的,你只需要将其添加为字符串,如果你打算使用命名函数。

This might not work below PHP 5.4 and you might need additional assignation e.g. $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);

这篇关于参考Array对PHP函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆