Home > Software engineering >  PHP - code optimisation - parameter "into" a function name (hum) or better method?
PHP - code optimisation - parameter "into" a function name (hum) or better method?

Time:08-12

I have a function, called function($parameter) for the example. I want this function to call another function, different depending on the parameter.

My code today:

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.

The "inside" function is always named in the same way. For the example, fctA(), fctB()... What is inside these functions is totally different the one with another.

Could I do better than that looooong list of "if" ? Using a variable into a function name seems impossible... but if there is a better method, I am eager to read about it! :)

Maybe I'm missing something obvious, any tips welcomed, I'm still learning!

Thanks a lot!

CodePudding user response:

You can call a function from your $parameter variable by using it in an interpolated string:

function ($parameter) {
  if (function_exists("fct{$parameter}")) {
    return "fct{$parameter}"();
  } else {
    return "Unknown Function: fct{$parameter}";
  }
}

If $parameter is A, this will call fctA(), if it is B it will call fctB(), and so on.

Only catch is to make sure you have a function for each possible value of $parameter, and they all have the same signature, such as function fctA() { return 'A'; }, function fctB() { return 'B'; }, etc etc. Thanks to enter image description here

  •  Tags:  
  • php
  • Related