Search code examples
phpdynamic-function

How to call a function from a string stored in a variable?


I need to be able to call a function, but the function name is stored in a variable, is this possible? e.g:

function foo ()
{
    //code here
}

function bar ()
{
    //code here
}

$functionName = "foo";
// I need to call the function based on what is $functionName

Solution

  • $functionName() or call_user_func($functionName)

    If you need to provide parameters stored in another variable (in the form of array), use array unpacking operator:

    $function_name = 'trim';
    $parameters = ['aaabbb','b'];
    echo $function_name(...$parameters); // aaa
    

    To dynamically create an object and call its method use

    $class = 'DateTime';
    $method = 'format';
    echo (new $class)->$method('d-m-Y');
    

    or to call a static method

    $class = 'DateTime';
    $static = 'createFromFormat';
    $date = $class::$static('d-m-Y', '17-08-2023');