Coding/Learn/php/php functions and type declarations
PHP Foundational Course
01.Introduction, Server-Side Architecture & Syntax
02.Variables, Strict Types & Dynamic Casting
03.Strings, Numbers & Built-in Math Functions
04.Operators, Null Coalescing & Magic Constants
05.Control Flow: If-Else, Switch & Modern Match Expressions
06.Loops: While, For & Foreach Traversal
07.Functions, Type Declarations & Named Arguments
08.Arrays & Functional Array Manipulation
09.Superglobals, Form Handling & Input Sanitization
10.Date, Time & DateTimeImmutable Objects
11.File System, Streams & I/O Operations
12.Cookies, Sessions & State Management
13.Exceptions, Throwables & Custom Error Fences
14.Classes, Objects & Constructor Property Promotion
15.Inheritance, Access Modifiers & Method Overriding
16.Interfaces, Abstract Classes & Polymorphism
17.Traits, Static Members & Namespaces
18.PDO, MySQL & Prepared Statements against SQL Injection
19.JSON & XML REST API Interoperability
20.Capstone: Production Secure Backend API & User Registry Engine
Course Certificate0%

Complete all lessons to earn

LearnFunctions, Type Declarations & Named Arguments
7 / 20 0%
Lesson 07 of 20
9 mins read

Functions, Type Declarations & Named Arguments

PreviousNext Lesson
In Plain English

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.

The Mental Model

"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.

PointCore Rules to Remember

Point star
Type Declarations: Prevents runtime bugs by strictly validating inputs and outputs at function boundaries.
Point star
Named Arguments: Enables skipping optional parameters with defaults and clarifies function call semantics.
Point star
Variadic Functions: function sum(...$numbers) gathers arbitrary arguments into a single array.

Common Beginner Traps & How to Fix Them

Mistake: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.

Pro Tip: Use arrow functions (fn($x) => ...) inside array_map and array_filter for clean, readable pipelines.

Live Interactive Example

Hit Run Code to see it live
Typed Function with Named Arguments & Arrow Closure
PHP 8.2 / CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Output Console
Click "Run Code" to view the rendered output.
How it works: Named argument shout: true bypassed default parameter positions cleanly, and arrow function doubled numbers.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Implement Typed Discount Calculator

  • PointDefine a function applyDiscount(float $price, float $percent = 10.0): float.
  • PointCalculate discount = price * (percent / 100) and return price - discount.
  • PointIn main script, call applyDiscount(price: 200.0, percent: 15.0) and print "Final Price: $[result]".
1
2
3
4
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates