簡體   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