gpt4 book ai didi

php - 带数字的函数名

转载 作者:行者123 更新时间:2023-12-05 01:02:52 25 4
gpt4 key购买 nike

有没有办法在循环中给函数名添加数字?

我试着这样做:

for($i=0;$i<$length;$i++){
{function.$i}();
}

谢谢

最佳答案

这个http://php.net/manual/en/functions.variable-functions.php需要“变量函数” .

PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.

看这个例子:http://3v4l.org/sGLtj

function my_function_0() { echo "0"; }
function my_function_1() { echo "1"; }
function my_function_2() { echo "2"; }
function my_function_3() { echo "3"; }

for($i=0;$i<4;$i++)
{
$calling = 'my_function_'.$i;
$calling(); // by adding parentheses, a function with the same name with $calling's value will be called
}

这将调用函数并输出0123

但请记住:

A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

http://3v4l.org/sGLtj

所以函数名可以带数字,只要函数名不以数字开头。

关于php - 带数字的函数名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26687418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com