PHP Call User Function

PHP call_user_func

With PHP, you can use call_user_func to call a function and use its parameters. The example below will demonstrate how it can be used with the str_replace() function. Under that, you will see how to use str_replace() to retrieve the same results.

In the first block, you will see that the function 'str_replace' is the first parameter, while the second, third and fourth parameters are those used by the str_replace function.  So, if you use str_replace() on its own, your parameters are find, replace, from string while the call_user_func() is the function name, find, replace, from string.

$a = 'testin'; 
$replaced = call_user_func('str_replace', 'in', '', $a); 
echo $replaced . "\n";   
$a = 'testin'; 
$replaced = str_replace("in", '', $a); 
echo $replaced . "\n";


Example #2

Here is a another example that uses a custom function called my_test(). Again, like the example above, it shows a tradition way to receive the desired results and the technique using call_user_func(). With this example, one variable is passed into the function and the same variable is returned with a new name. Finally, the variable is printed.

function my_test($input){ 
return $input; 
}  
$input = my_test('Bohemia'); 
echo $input . "\n";  
$example = call_user_func('my_test', 'Bohemia'); 
echo $example . "\n";


Example #3

This example is similar to the one above, except that two parameters are into the function; one called 'Bohemia2' and the $example variable that was created from the previous example.

function my_test2($input, $second) { 
return $input . $second; 
}  
$input2 = my_test2('Bohemia2', $example); 
echo $input2 . "\n";  
$example2 = call_user_func('my_test2', 'Bohemia2', $example); 
echo $example2 . "\n";


Output

test
test
Bohemia
Bohemia
Bohemia2Bohemia
Bohemia2Bohemia