Lab 03: Named Args & Intersection Types

Time: 40 minutes | Level: Advanced | Docker: docker run -it --rm php:8.3-cli bash

This lab covers PHP 8.0–8.2 syntax features: named arguments, intersection types, DNF types, the never return type, first-class callables, and array unpacking with string keys.


Step 1: Named Arguments — Basics

Named arguments let you pass values by parameter name, skipping optionals and clarifying intent:

<?php
function createUser(
    string $name,
    int    $age    = 0,
    string $role   = 'user',
    bool   $active = true
): string {
    $activeStr = $active ? 'active' : 'inactive';
    return "$name / age=$age / role=$role / $activeStr";
}

// Traditional positional
echo createUser('Alice', 30, 'admin', true) . "\n";

// Named — skip optionals, change order
echo createUser(name: 'Alice', role: 'admin') . "\n";
echo createUser(age: 25, name: 'Bob') . "\n";

// Mix positional + named (positional must come first)
echo createUser('Charlie', role: 'editor', active: false) . "\n";

📸 Verified Output:

💡 Named arguments also work with built-in functions: array_slice(array: $arr, offset: 2, preserve_keys: true).


Step 2: Named Arguments with Built-in Functions

📸 Verified Output:


Step 3: Intersection Types (PHP 8.1)

Intersection types require a value to satisfy multiple type constraints:

📸 Verified Output:

💡 Intersection type A&B means "must implement both A and B". Only interfaces and classes are allowed — no primitives.


Step 4: DNF Types (PHP 8.2)

Disjunctive Normal Form types combine intersection and union types:

📸 Verified Output:


Step 5: The never Return Type

never means a function never returns — it always throws or exits:

📸 Verified Output:

💡 never is useful for framework routing, assertion helpers, and HTTP error responses. The type system knows the function won't return.


Step 6: First-Class Callable Syntax (PHP 8.1)

Create closures from any callable with callable(...):

📸 Verified Output:


Step 7: Array Unpacking with String Keys (PHP 8.1)

📸 Verified Output:

💡 Later keys in the spread override earlier ones — same behavior as array_merge() but with cleaner syntax.


Step 8: Capstone — Type-Safe Transformation Pipeline

Combine named args, first-class callables, intersection types, and DNF types:

📸 Verified Output:


Summary

Feature
Syntax
PHP Version

Named arguments

fn(name: 'val', other: 1)

8.0+

Skip optional params

fn(first: 'a', third: 'c')

8.0+

Intersection type

A&B

8.1+

DNF type

(A&B)|null

8.2+

never return type

function fail(): never { throw ... }

8.1+

First-class callable

strlen(...)

8.1+

First-class static

Cls::method(...)

8.1+

First-class instance

$obj->method(...)

8.1+

String key array spread

[...$a, ...$b]

8.1+

Last updated