PHP User-defined function
PHP functions are blocks of code that perform specific tasks.
PHP has over 700 built in functions.
PHP also support user-defined functions.
Function are use for re-usability of same code for multiple times.
Syntax for PHP functions
1 2 3 4 5 6 7 8 9 |
<?php function function_name($arg1, $arg2,....,$arg_n) { //statements return $return_value; //optional } ?> |
Function definition starts with name function.
Function_name can be start with letters or underscore followed by any number of letters, numbers, or underscores.
Function_name can not be start with number.
Function names are case-insensitive.
Example
1 2 3 4 5 6 7 8 9 |
<?php function sum($a) { echo $a; //10 } sum(10); ?> |
In above example we create a function having name sum().
All the function body or function code is done within curly brace({});
‘{‘ opening curly brace indicates beginning of function code and ‘}’ closing curly brace indicates the end of the function.
Here we pass $a as argument to function.
Notes:
- Functions need not be defined before they are referenced.
- All PHP functions have global scope.
- PHP does not support function overloading.
- Also, it is not possible to redefine the previously-declared functions.
- It is possible to call recursive functions in PHP.
Example
1 2 3 4 5 6 7 8 9 10 |
<?php function recur_fun($x) { if ($x < 50) { echo "$x\n"; recur_fun($x + 2); } } ?> |