【问题标题】:PHP - code optimisation - parameter "into" a function name (hum) or better method?PHP - 代码优化 - 参数 \"into\" 一个函数名 (hum) 还是更好的方法?
【发布时间】:2022-08-12 00:20:06
【问题描述】:

我有一个函数,例如 function($parameter)。我希望此函数调用另一个函数,具体取决于参数。

我今天的代码:

function($parameter)
{
    if($parameter == \"A\")
    {
        fctA();
    }
    elseif($parameter == \"B\")
    {
        fctB();
    }
    elseif($parameter == \"C\")
    {
        fctC();
    }
}
// etc.
// There is a long list. Really long. Imagine that goes to ZZZZZ.

\"inside\" 函数总是以相同的方式命名。例如,fctA()、fctB()... 这些函数内部的内容与另一个完全不同。

我能比那个冗长的“if”列表做得更好吗? 在函数名中使用变量似乎是不可能的……但如果有更好的方法,我很想读一读! :)

也许我错过了一些明显的东西,欢迎任何提示,我仍在学习!

非常感谢!

    标签: php


    【解决方案1】:

    您可以通过在插值字符串中使用 $parameter 变量来调用函数:

    function ($parameter) {
      "fct{$parameter}"();
    }
    

    如果$parameterA,这将调用fctA(),如果它是B,它将调用fctB(),依此类推。

    唯一的问题是确保$parameter 的每个可能值都有一个函数,并且它们都具有相同的签名,例如function fctA() { return 'A'; }function fctB() { return 'B'; } 等。

    【讨论】:

    • 您可能希望使用function_exists 预先检查该函数是否存在,以便您可以更优雅地处理错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    相关资源
    最近更新 更多