Home >Backend Development >PHP Tutorial >php(4)——Function
Functions in PHP do not need to be defined before calling;
All functions and classes in PHP have global scope and can be defined within a function and called outside, and vice versa;
PHP does not support function overloading, and it is impossible to undefine or redefine declared functions;
Recursive functions can be called in PHP. But avoid recursive function/method calls beyond 100-200 levels as it may collapse the stack and terminate the current script.
function definition:
function function name ([parameter list]){
function body
}
PHP uses value passing by default, but it can also be passed by value Passing a reference (this method can change the passed parameter value in the function body)
For example:
function fun(&$var){
$var++;
}
$var = 0;
fun($var);
echo $var;
output 1;
PHP supports default parameter values.
For example:
function fun($var1,$var2=2,$var3=3){
return $var1+$var2+$var3;
}
echo fun(1) ;
echo fun(1,1);
echo fun(1,1,2);
will output 6 5 4 respectively
Note: Any default parameters must be placed to the right of any non-default parameters side; otherwise, the function will not work as expected.
If you change the above function to:
function fun($var2=2,$var3=3,$var1){
return $var1+$var2+$var3;
}
echo fun(1 );
echo fun(1,1);
echo fun(1,1,2);
Except the third calling method can be executed normally, the first two will cause problems.
PHP supports variable number of parameter lists.
Before PHP5.6, to obtain parameter information, you need to use func_num_args() to obtain the number of parameters, and func_get_arg(i) to obtain the value of the i-th parameter;
For example:
function fun( ){
$len = func_num_args();
$res = 0;
for($i = 0; $i<$len; $i++){
$res += func_get_arg($ i);
}
return $res;
}
introduced...$args method in PHP5.6,
such as:
function fun(. ..$args){
$res = 0;
foreach ($args as $val){
$res += $val;
}
return $res;
}
The results of both methods are the same.
The concept of variable functions in PHP
That is, if there are parentheses after a variable name, PHP will look for a function with the same name as the value of the variable and try to execute it. Variable functions can be used to implement some purposes including callback functions and function tables.
Example:
function fun(){
echo "Hello";
}
$var = "fun";
$var();//The fun() function will be called
Anonymous functions in PHP
Anonymous functions, also called closure functions (closures), allow you to temporarily create a function without a specified name. The value most commonly used as a callback function argument.
You can also specify the function name of the anonymous function through assignment, such as:
$fun = function (){
echo "HelloWorld";
};
$fun();
The above has introduced the php(4)-function, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.