PHP: Functions
What you will learn
How to define functions, use default parameters, type declarations, and variable scope.
Defining a function
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice"); // Hello, Alice!
Functions are defined with the function keyword. Parameters do not need type declarations (though they can have them).
Default parameters and type hints
function power(int $base, int $exp = 2): int {
return $base ** $exp;
}
echo power(3); // 9
echo power(3, 3); // 27
Type hints (int $base) force the argument to be that type, and : int declares the return type.
Variable scope
Variables defined outside a function are not available inside by default:
$prefix = "Hello";
function greet($name) {
global $prefix; // must declare global
return "$prefix, $name!";
}
Better: pass variables as parameters instead of using global.
Anonymous functions / closures
$double = function($n) {
return $n * 2;
};
echo $double(5); // 10
// Arrow function (PHP 7.4+)
$triple = fn($n) => $n * 3;
echo $triple(5); // 15
Common mistakes
- Calling a function before it's defined — PHP does hoist function declarations
- Forgetting to
returna value — the function returnsnull - Using
globalwhen passing as a parameter is cleaner - Naming collisions with built-in PHP functions (always check the manual first)
Quick check below!