Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function name with number

Tags:

php

There is a way to add number to function name in loop?

I tried to do it this way:

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

Thank you

like image 730
perkle Avatar asked Feb 10 '26 21:02

perkle


1 Answers

You need "Variable functions" for this 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.

See this example: 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
}

this will call the functions and will output 0123

But keep in mind that:

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

http://3v4l.org/sGLtj

So you can have function name with number, as long the function name does not start with a number.

like image 165
Sharky Avatar answered Feb 13 '26 10:02

Sharky