user8325878
user8325878

Reputation:

How to use variable function-name in a loop?

I have made this loop with PHP OOP:

for($i=1;$i<=5;$i++){ 
echo "
    <tr>
    <td>$i</td>
    <td>".$menuSet->GetMenuLink1()."</td>
    <td>
        <a title='Edit' href='#'><span class='glyphicon glyphicon-pencil'></span></a>&nbsp; 
        <a title='Remove' href='#'><span class='glyphicon glyphicon-remove'></span></a>
    </td>
    </tr>
";
// replace $menuSet->GetMenuLink1() with another variable
}

And as you can see I want to replace $menuSet->GetMenuLink1() variable with $menuSet->GetMenuLink2() and this loop goes till $menuSet->GetMenuLink5().

(Add 1 to GetMenuLink function)

So how can I do this in php ?

Upvotes: 0

Views: 297

Answers (3)

nerdlyist
nerdlyist

Reputation: 2847

PHP actually is very liberal in calling functions from variables. I cannot remember what it is called off the top of my head but you can do this:

for($i=1;$i<=5;$i++){ 
    $func = "GetMenuLink".$i;
echo "
    <tr>
    <td>$i</td>
    <td>".$menuSet->$func()."</td>
    <td>
        <a title='Edit' href='#'><span class='glyphicon glyphicon-pencil'></span></a>&nbsp; 
        <a title='Remove' href='#'><span class='glyphicon glyphicon-remove'></span></a>
    </td>
    </tr>
";
// replace $menuSet->GetMenuLink1() with another variable
}

** Not sure this is a great idea you may want to look into other patterns though

Upvotes: 0

Qirel
Qirel

Reputation: 26450

This sounds like a really bad design-pattern - you should avoid it if at all possible. But it is doable the way you ask it. To do it properly, you should rebuild you function to take an argument which you use, so you have GetMenuLink(1) and GetMenuLink(2) instead of GetMenuLink1() and GetMenuLink2().

function getMenuLink($i) {
    // Code for the function goes here
    // Adapt for usage of an arugment, e.g. if ($i == 1) { ... }
    // Use $i to get the link you wish to produce
}

If that's for some obscure reason not possible, define a variable with the name of the function, and use that as $variable(), like shown below. This is called a variable function. However, I strongly recommend you just rebuild your function to take an argument instead, and avoid a solution like this.

for ($i=1; $i <= 5; $i++){
    $method_name = "GetMenuLink".$i;
    echo "
        <tr>
        <td>$i</td>
        <td>".$menuSet->$method_name()."</td>
        // .....

Upvotes: 1

Bytewave
Bytewave

Reputation: 597

Although this isn't exactly the greatest design, you could use call_user_func and an array containing the method you want to call. In your case, you could do something like:

call_user_func(array($menuSet, 'GetMenuLink' . $i));

which uses PHP's callable arrays.

Personally, however, I would recommend refactoring this. Do this processing in the class, in a method named GetMenuLinks or similar.

Upvotes: 0

Related Questions