➤ Besides the built-in PHP functions, it is possible to create your own functions.
• A function is a block of statements that can be used repeatedly in a program.
• A function will not execute automatically 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:
function
functionName() {
code to be executed;
}
functionName() // Calling a function
For instance:
function printMyName() {
echo "My name is Levani :))\n";
}
printMyName(); // calling a function
➤ Function Arguments
Information can be passed to functions through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a comma.
For instance:
// Function with parameters
function printInfo($firstName,$lastName,$age){
echo "Hello,my name is $firstName $lastName, I am $age years old :))\n";
}
// Arguments
printInfo("Levani","Makhareishvili",19);
$name = "Mads";
$lastName = "Mikkelsen";
$age = 56;
printInfo($name,$lastName,$age);
➤ Note the difference between parameters and arguments:
• Function parameters are the names listed in the function's definition.
• Function arguments are the real values passed to the function.
• Parameters are initialized to the values of the arguments supplied.
➤ The advantages of using functions are:
• Functions reduces the repetition of code within a program
• Functions makes the code much easier to maintain
• Functions makes it easier to eliminate the errors
• Functions can be reused in other application