Home > other >  declaring functions inside a loop in php
declaring functions inside a loop in php

Time:02-08

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 by for 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.

CodePudding user response:

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";
}

CodePudding user response:

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

  •  Tags:  
  • Related