Menü schliessen
Created: July 18th 2018
Last updated: May 1st 2020
Categories: Common Web Development,  IT Development
Author: Marcus Fleuti

PHP function's name as a variable

Tags:  function,  PHP,  variable
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Sometimes there is a need to call too many functions based on some parameter. We can use huge amount of if/else statements or switch statement wit a lot of cases in order to call some function based on some parameter.

switch ($parameter) {
    case "parameter_1":
        function_1();
    break;
    case "parameter_2":
        function_2();
    break;
    case "parameter_3":
        function_3();
    break;
    ...
}

This is a valid code but image that we have over 300 functions here called with over 300 different parameters. Code would be too long and it isn't practical.
Solution is quite simple - we can use variables as function names.

$func = 'foo';
$func();        // This calls foo()

In this case, it doesn't matter how much different parameters we have - we just need to make sure that we have defined functions for each parameter (in this case function would be foo() ).

This method has some limitations, as it's stated in documentation: it cannot be used with language constructs such as echoprintunset()isset()empty()includerequire and the like. We can use wrapper functions in order to call these.