Besides the built-in PHP functions, we can create our own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.
A user defined function declaration starts with the word function
:
A function name can start with a letter or underscore (not a number).
Give the function a name that reflects what the function does!
function functionName() {
//statements;
}
Function names are case-insensitive, though it is usually good form to call functions as they appear in their declaration.
A function can be called with it's name followed by ( )
.
A user defined function can call as follows:
functionName(); // calling function
This example defines a function named printMsg
witch prints a message "Hello World!".
In 5th line printMsg();
is call the function defined above.
<?php
function printMsg() {
echo "Hello World!";
}
printMsg(); // call the function
?>
To let a function return a value, use the return statement:
function functionName() {
//statements;
return;
}
This example defines a function named add
having two argument $a
and $b
, witch is initializes with value given from function call ($a = 5, $b = 7).
The statement $c = $a + $b;
Inside body of the function performs addition of $a and $b and final value is assign to $c.
Last line of function returns value of $c
, which is returned to were function is called, and assigns the value to $ans
.
Finally we get the answer and we print it using echo statement.
<?php
function add($a, $b) {
$c = $a + $b;
return $c;
}
$ans = add(5, 7); // call the function
echo "Addition of 5 + 7 = $ans";
?>
Ask Question