PHP Function Advanced
Nested function
In PHP, a function can call another function so you can modulize your code more flexibile and resuable. In PHP, a function also can be nested inside another function as well. Let's take a look at the following example:
<?php
function find_max($a,$b,$c){
// find max of two arguments
function max($x,$y){
return $x > $y ? $x : $y;
}
//
return max(max($a,$b),$c);
}
echo max(3,20,7);
?>
The function find_max() is used to find maximum value of three input arguments. Inside the function, we have anther nested function to find maximum values of two input arguments max(). First we find maximum value of the first and the second argument by using the nested function max(). Then we find maximum value of the maximum value of the first and the second arguments and the third argument also by nested function max().
Recursive function
A function in PHP can call itself. If the function call itself inside the function body, we have a recursive function. A recursive function is used to solve problem by dividing the big problem into smaller solvable problem, and solve all smaller solvable problem until the big problem sovled.
Variable function
In PHP, a variable function is a function whose name is evaluated before execution. Consider the following example:
<?php
function find_max($a,$b){
return $a > $b ? $a : $b;
}
function find_min($a,$b){
return $a < $b ? $a : $b;
}
$f = "find_max";
echo $f(10,20); // 20;
$f = "find_min";
echo $f(10,20) // 10;
?>
We have two functions, find maximum and minimum values of two input arguments. In line 9, we have a string variable $f whose value is the name of function find_max(). In line 10 we call the function find_max() through variable $f. In line 11, we assign variable $f to the name of function find_min() and then we call the function find_min() through variable $f. So the variable $f in both cases is cheated as a function.
Variable function brings flexibility in some programming context where you need to call a specific function based on a certain condition. But variable function also brings security risk.