User Define Function in PHP
|
Function is a collection of logically related statements that are used to perform specific task. |
||||||||
How to define Function |
||||||||
|
In PHP there
is no need to declare user define function like C and C++.
Syntax
function FunctionName(ArgumentList) { Function Body (Group of Statements) } Argument List
is a collection of variables seperated by commas.If function does not pass any arguments
then parenthesis are left blank.
Syntax
FunctionName(Argument) Now consider
simple example using user define function that display welcome meddage in PHP script.
Example <?php //Function Definition function Message() { echo "Welcome To the World of PHP"; } //Function Call Message(); ?> Output Welcome TO the World of PHP |
||||||||
| Function with Arguments | ||||||||
|
Sometimes it
is required to pass different input values to the function so function can work
with that values.This can be done by passing arguments to the function.
Example <?php //Function Declaration function sum($a,$b) { $c=$a + $b; echo "Sum=".$c; } //Function Call sum(3,4); //Function Call sum(5,4); ?> Output Sum = 7 Sum = 9 |
||||||||
| Function with Return value | ||||||||
|
Sometimes it
is required to return value from the function to the point from which the function
is called. In PHP function can return a single value. Example <?php //Function Declaration function sum($a,$b) { $c=$a + $b; return $c; } $a = 4; $b = 5; //Function Call echo "sum of $a and $b is ".sum($a,$b); $a = 5; $b = 3; //Function Call echo "sum of $a and $b is ".sum($a,$b); ?> Output Sum of 4 and 5 is 9 Sum of 5 and 3 is 8 |
||||||||
| Function with Default Argument | ||||||||
|
The process
of assigning value to the argument at the time of defining function is known as
default argument function.
Syntax
function FunctionName(Argument1, Argument2=DefaultValue) { Function Body (Group of Statement) } Note: Default argument must be specified after all non default arguments. Consider following
example which calculate area of circle using default argument.
Example <?php //Function Declaration function Area($r, $pi=3.14) { $a = $pi * $r; return $a; } //Function Call $r=3; echo "Area of Circle with Radius $r is".Area($r); ?> Output Area of Circle with Radius 3 is 28.26 |
||||||||
| Function with Variable Length Argument | ||||||||
|
In PHP you
can pass variable number of arguments to the function without defining it in function
definition.
Consider following
example which will concate all the arguments that are passed to the function.
Example <?php //Function Definition function Concate() { $n = func_num_args(); echo "$n arguments passed to the function<br/>"; $m = ""; $arg = func_get_args(); foreach ($arg as $value) { $m = $m.$value; } return $m; } //Function Call echo concate ("PHP", "Server", "Side","Scripting","Language"); ?> Output 5 arguments passed to the function PHP Server Side Scripting Language |