PhPHP · Lesson 4 of 8

Functions & Type Declarations

Modern PHP functions look almost like TypeScript: typed parameters, return types, default and named arguments. Use the types — they turn silent bugs into loud errors.

PHP
<?php
declare(strict_types=1);   // put this at the top of every file

function greet(string $name, int $times = 1): string {
    return str_repeat("Hello, $name! ", $times);
}

echo greet("Ada");            // Hello, Ada!
echo greet("Ada", times: 3);  // named argument (PHP 8)

greet(42);   // TypeError — thanks to strict_types

// Nullable and union types:
function findUser(int $id): ?string { /* string or null */ }
function parse(string|int $input): array { /* union type */ }
◆ Note
Without declare(strict_types=1), PHP silently coerces arguments ('42' becomes 42). With it, wrong types throw. Every modern codebase turns it on — make it a habit from day one.
PHP
<?php
// Anonymous functions and closures:
$multiply = function (int $a, int $b): int {
    return $a * $b;
};
echo $multiply(3, 4);   // 12

// Long closures need 'use' to capture variables:
$factor = 10;
$scale = function (int $n) use ($factor): int {
    return $n * $factor;
};

// Arrow functions capture automatically:
$scale2 = fn(int $n) => $n * $factor;

// Variadics and spread:
function sum(int ...$nums): int {
    return array_sum($nums);
}
sum(1, 2, 3);            // 6
sum(...[4, 5, 6]);       // 15