Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP – code optimisation – parameter "into" a function name (hum) or better method?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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 @jhmckimm for the function_exists suggestion; that is a good way to handle that.

Funcional example:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading