Home > Software engineering >  PHP Call function from another function
PHP Call function from another function

Time:09-28

Need to create function that will call other built-in and custom functions, problem is that each called function has different number of parameters.

I supply to a callerFunction required function name and required parameters in array, but how do i implement the actual function call?

P.S. I am aware of function scope, this is not a question now.

    function myFunction(inputStr, paramOne, paramTwo) {
        echo inputStr . " P1: " . paramOne . " P2: " . paramTwo;
    }
    
    
    function callerFunction(functName, functArgsArr) {
    
        $myVar = "";
        n = 1;
        
        while n <= functArgsArr.length {

            myVar = myVar . " " . functArgsArr[n];

            n  ;

        }

        %functName%("Hello World!", %myVar%);
    }

callerFunction("myFunction", ["one", "two"]);

CodePudding user response:

You could use the call_user_func_array PHP function:

<?php

function myFunction($inputStr, $paramOne, $paramTwo)
{
    echo $inputStr . " P1: " . $paramOne . " P2: " . $paramTwo;
}

function callerFunction($functionName, array $functArgsArr)
{
    // Prepends 'Hello World' to args array
    array_unshift($functArgsArr, "Hello World");
    
    // Calls $functionName passing the values of $functArgsArray as arguments
    call_user_func_array($functionName, $functArgsArr);
}

callerFunction("myFunction", ["one", "two"]);

Working PHP Fiddle

  • Related