Functions
Functions are the building blocks of every PHP program. Modern PHP functions can declare the types of their parameters and return values, take named arguments, and be passed around as values. Using types well catches bugs before they reach your users.
Defining functions
string $namedeclares the parameter type;: stringthe return type.- Functions without a return type return
nullif there's noreturn; use: voidto say "returns nothing".
Types and strict_types
By default, PHP converts arguments to the declared type when it can. With declare(strict_types=1) at the top of the file, the types must match exactly:
💡 Put
declare(strict_types=1);at the top of every file. Mistakes then fail loudly at the call that caused them, instead of producing strange values later.
Richer types
| Type | Allows |
|---|---|
int, float, string, bool, array |
The basic types |
?string |
A string or null |
int|float |
Either (union type) |
mixed |
Anything |
void |
Returns nothing |
never |
Never returns (always throws or exits) |
callable, iterable, a class name |
Functions, loops, objects |
Default values and named arguments
Named arguments (PHP 8) make calls self-explanatory and let you skip optional parameters. They work with built-in functions too.
Passing by value and by reference
Arguments are copied (including arrays). Prefix a parameter with & to modify the caller's variable:
Returning a new value is usually clearer than references. (Objects behave differently: a function receives a handle to the same object, as you'll see in Object-oriented PHP.)
Anonymous functions, closures and arrow functions
Functions are values: store them in variables and pass them to other functions.
- A closure (
function () use ($x) { … }) captures variables by value when it's created. - An arrow function (
fn($x) => …) is a single expression and captures variables automatically. strlen(...)turns any function or method into a callable.
Counter: a closure with state
Static variables and recursion
Built-in functions
PHP ships with thousands of functions. Some you'll use every day:
php.net has a page for every function, with examples. Search "php" plus the function name.
Practice
- Write
function bmi(float $kg, float $m): floatwithstrict_typesand return the BMI rounded to 1 decimal. - Write
function formatPrice(int $cents, string $currency = "₹"): stringand call it with a named argument. - Write
function average(int|float ...$numbers): floatthat returns0.0when called with no numbers. - Use
array_filterwith an arrow function to keep only the words longer than 4 letters.
1.What does declare(strict_types=1) change?
2.What does ?string mean as a type?
3.How does an arrow function fn($x) => $x * $rate get $rate?
4.What does makeCoffee(milk: false) do?