perkle
perkle

Reputation: 41

Function name with number

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

Upvotes: 3

Views: 6723

Answers (2)

user1180790
user1180790

Reputation:

To call a function, which name is generated as a string, use call_user_func function, passing the generated string as its first argument.

Example

function function0(){echo "Function 0\n";}
function function1(){echo "Function 1\n";}
function function2(){echo "Function 2\n";}

for($i = 0; $i < 3; ++$i){
    call_user_func('function' . $i);
}

Upvotes: 1

Sharky
Sharky

Reputation: 6274

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.

Upvotes: 8

Related Questions