Declaring Functions

Declaring Functions and Default Parameters

Function names are case-insensitive, and a top-level function can be called above its declaration because PHP compiles the whole file first; one declared inside an if or another function exists only once that code runs. A parameter with = is optional and must follow the required ones, or PHP reports Optional parameter $a declared before required parameter $b is implicitly treated as a required parameter. Since 8.1 a default may be a new expression, and since 8.3 a static variable, which keeps its value between calls, may start from any expression.

Defaults, a new-expression default and a static counterPHP
<?php
declare(strict_types=1);
echo shout('Hello'), ' ', SHOUT('Hi', 'She says: ', '.'), "\n";   // before its declaration
function shout(string $s, string $prefix = 'I say: ', string $end = '!'): string
{
  return $prefix . $s . $end;
}
function nextInvoice(DateTimeImmutable $at = new DateTimeImmutable()): string   // PHP 8.1+
{
  static $n = (int) $at->format('Y') * 1000;   // any expression, PHP 8.3+
  return 'INV-' . ++$n;
}
echo nextInvoice(), ' ', nextInvoice(), "\n";
Output
I say: Hello! She says: Hi.
INV-2026001 INV-2026002

A new default is evaluated on each call that omits the argument; the static initializer runs once per request, so it is no cross-request cache.