PHP function is a piece of code that can be reused many times.
Advantage of PHP Functions:
- Code Reusability
- Less Code
- Easy to understand
You can define a function using the function keyword:
1. Defining a Function:
You can define a function using the function keyword
<?php
function greet() {
echo "Hello, World!";
}
?>
2. Function Parameters:
You can pass parameters to a function:
<?php
function greetWithName($name) {
echo "Hello, $name!";
}
// Call the function with an argument
greetWithName("John");
?>
3. Return Values:
Functions can return values:
<?php
function add($a, $b) {
return $a + $b;
}
$result = add(3, 5);
echo "Sum: $result"; // Outputs: Sum: 8
?>
4. Variable Scope:
Variables declared inside a function have local scope and are not accessible outside the function:
<?php
function example() {
$x = 5; // Local variable
echo $x;
}
example(); // Outputs: 5
// echo $x; // This would cause an error
?>
5. Global Keyword:
You can use the global keyword to access global variables within a function:
<?php
$globalVar = 10;
function accessGlobal() {
global $globalVar;
echo $globalVar;
}
accessGlobal(); // Outputs: 10
?>
6. Static Keyword:
The static keyword allows a variable to retain its value between function calls:
<?php
function increment() {
static $counter = 0;
$counter++;
echo $counter;
}
increment(); // Outputs: 1
increment(); // Outputs: 2
?>
7. Anonymous Functions (Closures):
You can create functions without a name:
<?php
$add = function($a, $b) {
return $a + $b;
};
echo $add(3, 4); // Outputs: 7
?>
8. Function Arguments by Reference:
You can pass arguments by reference using the & symbol:
<?php
function addTen(&$num) {
$num += 10;
}
$value = 5;
addTen($value);
echo $value; // Outputs: 15
?>
9. Recursive Functions:
Functions can call themselves
<?php
function factorial($n) {
if ($n === 0 || $n === 1) {
return 1;
} else {
return $n * factorial($n - 1);
}
}
echo factorial(5); // Outputs: 120
?>
These are fundamental concepts related to PHP functions.