Python Functions, Type Declarations & Named Arguments
Functions encapsulate reusable logic. Master typed parameters (int, string, ?array), return types (: void, : string), union types (int|float), variadic parameters (...$items), arrow functions (fn() =>), and PHP 8 named arguments.
"A typed function is like a certified vending machine slot: it strictly specifies that only a 25-cent coin fits, and guarantees a cold beverage drops out of the dispenser."
Deep Dive: How It Works
Type Signatures: Enforces argument types and return types (e.g. function add(int $a, int $b): int).
Nullable Types: Prefix types with ? (e.g. ?string $name allows string or null).
Union Types (PHP 8): int|float $number allows multiple valid types.
Named Arguments (PHP 8): Call functions by parameter name (formatUser(name: "Alice", active: true)).
Arrow Functions: Concise one-liner closures fn($x) => $x * 2 that automatically capture parent scope variables by value.
Syntax Blueprint
<?php
function calculateTax(float $subtotal, float $rate = 0.08): float {
return $subtotal * $rate;
}
$tax = calculateTax(subtotal: 100.0, rate: 0.10);Define parameter and return types with defaults, and invoke with named arguments.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Passing null to a non-nullable parameter type (e.g. string $str without ?).Why it happens: PHP throws a TypeError unless the type is explicitly declared as nullable (?string or string|null).
How to fix: Use ?string when a parameter or return value can legitimately be null.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Implement Typed Discount Calculator
Define a function applyDiscount(float $price, float $percent = 10.0): float.
Calculate discount = price * (percent / 100) and return price - discount.
In main script, call applyDiscount(price: 200.0, percent: 15.0) and print "Final Price: $[result]".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.