Skip to content
Advertisement

PHP processing with multiple function to return expected result

in this code which is that a simple code to work with passing multiple function we should expected to return 5 in result,

this below method should accept a one variable number of functions, and that should return a new function that accepts one parameter which that $arg named

the returned function should call the first function in the pipeline with the parameter $arg and call the second function with the result of the first function

the returned function should calling each function in the pipeline in order, following the same pattern and return the value from the last function

function pipeline(...$funcs)
{
    return function($arg) use ($funcs)
    {
        return -1;
    };
}

$fun = pipeline( function($parameter) { return $parameter * 3; },
                      function($parameter) { return $parameter + 1; },
                      function($parameter) { return $parameter / 2; } );
echo $fun(3); # we should see 5 in output

now whats problem of this code which that return -1

Advertisement

Answer

Because the returned function returns -1 and the functions are never called. You should loop over the functions and call them to alter $arg:

function pipeline(...$funcs)
{
    return function($arg) use ($funcs)
    {
        foreach ($funcs as $func) {
            $arg = $func($arg);
        }
        return $arg;
    };
}

$fun = pipeline(function($parameter) { return $parameter * 3; },
                function($parameter) { return $parameter + 1; },
                function($parameter) { return $parameter / 2; });
echo $fun(3); # we should see 5 in output

Output:

5
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement