PHP Tutorial · Functions and Arrays · Lesson 17 of 38
PHP Functions
Define functions with typed parameters, defaults, named arguments and return types.
Defining functions
<?php
function greet(string $name): string
{
return "Hello, $name!";
}
echo greet("Ada"), "\n";
Output
Hello, Ada!
Type declarations
Declare parameter and return types. With declare(strict_types=1); PHP rejects wrong types instead of converting them. Types include int, float, string, bool, array, class names, nullable ?string, unions int|float, and void.
Defaults and named arguments
Parameters can have default values. PHP 8 named arguments let you pass arguments by name, in any order, skipping optional ones:
<?php
function makeTag(string $text, string $tag = "p", ?string $class = null): string
{
$attr = $class ? " class=\"$class\"" : "";
return "<$tag$attr>$text</$tag>";
}
echo makeTag("Hi"), "\n";
echo makeTag("Title", "h1"), "\n";
echo makeTag("Note", class: "muted"), "\n";
Output
<p>Hi</p> <h1>Title</h1> <p class="muted">Note</p>
Variadic functions
...$numbers collects any number of arguments into an array; ...$array spreads an array into arguments:
<?php
function total(float ...$amounts): float
{
return array_sum($amounts);
}
echo total(1.5, 2.5, 3), "\n";
$cart = [10, 20, 5];
echo total(...$cart), "\n";
Output
7 35
Anonymous and arrow functions
Closures can be stored in variables and passed to functions like array_map(). Arrow functions (fn) capture outer variables automatically; classic closures need use:
<?php
$rate = 1.2;
$withTax = fn(float $p): float => $p * $rate;
$discount = function (float $p) use ($rate): float {
return $p / $rate;
};
print_r(array_map($withTax, [10, 20]));
echo $discount(120), "\n";
Output
Array
(
[0] => 12
[1] => 24
)
100Test yourself
Which PHP 8 feature lets you call makeTag('Hi', class: 'x')?
Default parametersNamed argumentsVariadic functionsClosures
Show answer
Answer: Named arguments