繁体   English   中英

如何在循环中使用变量function-name?

[英]How to use variable function-name in a loop?

我已经用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
}

正如你可以看到我想要替换$menuSet->GetMenuLink1()与变量$menuSet->GetMenuLink2()和这个循环,直到去$menuSet->GetMenuLink5()

(向GetMenuLink函数添加1)

那么如何在php中做到这一点呢?

这听起来像是一个非常糟糕的设计模式- 尽可能避免使用它 但这是您所要求的方法。 要正确执行此操作,您应该重建函数以使用要使用的参数,因此您具有GetMenuLink(1)GetMenuLink(2)而不是GetMenuLink1()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
}

如果由于某种晦涩的原因而无法实现,请定义一个带有函数名称的变量,并将其用作$variable() ,如下所示。 这称为变量函数 但是,我强烈建议您仅重建函数以采用参数,并避免采用此类解决方案。

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

尽管这并不是最好的设计,但您可以使用call_user_func和包含要调用的方法的array 就您而言,您可以执行以下操作:

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

它使用PHP的callable数组。

但是,就我个人而言,我建议对其进行重构。 在类中,使用名为GetMenuLinks或类似方法的方法进行此处理。

实际上,PHP从变量调用函数非常自由。 我不记得那是什么,但您可以执行以下操作:

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
}

** 不确定这是个好主意,尽管您可能想研究其他模式

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM