CourseLecture PHP Functions
CourseLecture PHP Functions
PHP Functions
What is a Function in PHP?
PHP function is a piece of code that can be reused
many times. It can take input as argument list and
return value.
PHP function can define Conditional function,
Function within Function and Recursive function
Advantage of PHP functions
• Code Reusability: PHP functions are defined only
once and can be invoked many times, like in other
programming languages.
• Less Code: It saves a lot of code because you don't
need to write the logic many times. By the use of
function, you can write the logic only once and reuse
it.
PHP Function Syntax:
function functionname()
{
//code to be executed
}
Note: Function name must be start with letter and underscore only like
other labels in PHP. It can't be start with numbers or special symbols.
Creating and Calling Function
Example:
Php Script Output
/* Calling a Function */
CreateMessage();
?>
PHP Function Arguments
We can pass the information in PHP function through
arguments which is separated by comma.
PHP supports :
Call by Reference
Default argument values
Variable-length argument list.
PHP Function Arguments
Example:
Php Script Output
SUMFunction(5, 45);
?>
Passing Arguments by Reference
• It is possible to pass arguments to functions by
reference.
• A reference to the variable is manipulated by the
function rather than a copy of the variable's value.
• Any changes made to an argument in these cases will
change the value of the original variable.
• You can pass an argument by reference by adding an
ampersand “&” to the variable name in either the
function call or the function definition.
Passing Arguments by Reference
Example:
Php Script Output
<?php
function PlusFive($num) {
Default Value is 10
$num += 5; Passing Value is 20
}
function PlusTen(&$num) {
$num += 10;
}
$defaultValue = 10;
PlusFive( $defaultValue );
PlusTen( $defaultValue);
echo "Passing Value is $defaultValue<br />";
?>
Funtions Returning Values
• A function can return a value using the return
statement in conjunction with a value or object.
return stops the execution of the function and sends
the value back to the calling code.
• You can return more than one value from a function
using return array(1,2,3,4)
Function Return Values
Example:
Php Script Output