Unlock reusable code - Functions organize logic, manage data, and streamline your PHP projects!
Functions are reusable blocks of code that perform specific tasks. They can take inputs (parameters), process them, and return outputs. PHP offers built-in functions and lets you create custom ones!
Use the function keyword, a name, and optional parameters.
function greet($name) {
echo "Hello, $name!";
}
greet("User"); // Outputs: Hello, User!Return a value using the return statement.
function add($a, $b) {
return $a + $b;
}
$result = add(5, 3);
echo $result; // Outputs: 8Return multiple values as an array.
function getStats() {
return ["score" => 95, "level" => 3];
}
$stats = getStats();
echo $stats["score"]; // Outputs: 95Use list() to unpack array returns (older style).
function getCoordinates() {
return [10, 20];
}
list($x, $y) = getCoordinates();
echo "X: $x, Y: $y"; // Outputs: X: 10, Y: 20Note: Modern PHP favors array destructuring:
[$x, $y] = getCoordinates();
Return a variable by reference with &.
function &getValue() {
static $value = 42;
return $value;
}
$ref = &getValue();
$ref = 100;
echo getValue(); // Outputs: 100Variables have scope—local by default.
$globalVar = "Outside";
function testScope() {
$localVar = "Inside";
echo $localVar; // Outputs: Inside
}
testScope();
echo $globalVar; // Outputs: Outside
// echo $localVar; // Error: UndefinedUse global or the $GLOBALS array.
$count = 5;
function increment() {
global $count;
$count++;
}
increment();
echo $count; // Outputs: 6With $GLOBALS:
$count = 5;
function incrementGlobals() {
$GLOBALS["count"]++;
}
incrementGlobals();
echo $count; // Outputs: 6Retain values between calls with static.
function counter() {
static $num = 0;
$num++;
return $num;
}
echo counter(); // Outputs: 1
echo counter(); // Outputs: 2Functions with conditional logic.
function checkAge($age) {
if ($age >= 18) {
return "Adult";
}
return "Minor";
}
echo checkAge(20); // Outputs: AdultCall functions dynamically by name.
function sayHello() {
echo "Hello!";
}
$funcName = "sayHello";
$funcName(); // Outputs: Hello!Define functions inside others (rarely used).
function outer() {
function inner() {
echo "Nested!";
}
inner();
}
outer(); // Outputs: Nested!Caution: Inner functions become global after
outer()runs once.
Move functions to separate files.
helpers.php:
function multiply($a, $b) {
return $a * $b;
}Main file:
include "helpers.php";
echo multiply(4, 5); // Outputs: 20Return error indicators (e.g., false, exceptions).
function divide($a, $b) {
if ($b == 0) {
return false; // Error indicator
}
return $a / $b;
}
$result = divide(10, 0);
if ($result === false) {
echo "Error: Division by zero!";
} else {
echo $result;
}
// Outputs: Error: Division by zero!With exceptions:
function safeDivide($a, $b) {
if ($b == 0) {
throw new Exception("Division by zero!");
}
return $a / $b;
}
try {
echo safeDivide(10, 0);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
// Outputs: Error: Division by zero!| Topic | Key Feature | Example Use Case |
|---|---|---|
| Returning Data | Single value | Calculations |
| Arrays | Multiple values | Data bundles |
| References | Modify original data | Memory optimization |
| Static Variables | Persist across calls | Counters |
| Variable Functions | Dynamic calls | Callbacks |
| Include Files | Reuse across files | Modular code |
- Naming: Use clear, verb-based names (e.g.,
calculateTotal). - Scope: Minimize
globaluse—pass parameters instead. - Errors: Prefer exceptions over
falsefor modern code. - DRY: Don’t Repeat Yourself—use functions to reuse logic.
function formatName($first, $last) {
return ucfirst($first) . " " . ucfirst($last);
}
echo formatName("john", "doe"); // Outputs: John Doe