'Declaring functions inside a loop in php

Suppose, I've a function like this -

function something() {
       
}

Now, I need to loop this function by changing the function name like this -

function something1() {
       
}

function something2() {
       
}

function something3() {
       
}

function something4() {
       
}

Is it possible to declare functions by loop ?? There are some other code staffs which is already looping inside of the for loop. But I can't change function names dynamically. Most importantly, I can't declare functions separately. I must do it inside a loop.

Can you help me to figure out that how can I do it??

Thanks.



Solution 1:[1]

I'm not sure what your asking precisely, because declaring is different from looping, but...

In case you want to call a function by a variable name, you can achieve this by using the concept of variable functions. See https://www.php.net/manual/en/functions.variable-functions.php for more information.

<?php

function something1()
{
    echo 'First';
}

function something2()
{
    echo 'Second';
}

function something3()
{
    echo 'Third';
}

function something4()
{
    echo 'Fourth';
}

for ($i = 1; $i < 5; $i++) {
    $functionName = "something$i";
    echo $functionName() . " function is called.\n";
}

Solution 2:[2]

I Suppose you need to MASS Declare functions. but that may not be performant and is probably not the right way. you can use FUNCTION ARGUMENTS instead.

function something ($number) {
     // Do Something With The Number you got.
}

for($i = 0; $i <= 10; $i++) {
    something($i); // pass the number to the function.
}

This is one of the ways of achieving this performantly. You Can Learn more about it here: Function Arguments

EDIT

Although, this is not the best practice, but you can declare dynamic functions, but not in the form of functions really:

<?php
for ($i = 0; $i <= 10; $i++) {
    $func_name = "something$i";
    $$func_name = function ($i) {
        echo "Hello the number is: $i";
    };
    // And call it like
    print_r($$func_name($i));
}

The double $$ is not a typo but a feature provided by PHP.

So for example:

$a = "b";

Then

$$a = "Hello";

Will evaluate to

$"b"

which would be processed by PHP like this: $b = "Hello"

And we are using that feature with functions instead.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DigiLive
Solution 2