Skip to content

01: Partial Function Application

Configure a log formatter once and reuse it as a callback. PHP 8.6 adds placeholders that turn a call with unfilled arguments into a Closure.

  • PHP 8.6 CLI. Confirm the version with php --version.

Allow about 10 minutes for the walkthrough and exercise.

A runnable partial-function-application.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/01-partial-function-application/partial-function-application.php
partial-function-application.php
<?php
declare(strict_types=1);
function formatLog(string $channel, string $level, string $message): string
{
return "$level [$channel] $message";
}
$workerLog = formatLog('worker', ...);
echo $workerLog('INFO', 'Job started'), PHP_EOL;
$billingError = formatLog('billing', 'ERROR', ?);
echo $billingError('Payment declined'), PHP_EOL;
$amounts = [1.235, 7.5];
print_r(array_map(round(?, 2), $amounts));
INFO [worker] Job started
ERROR [billing] Payment declined
Array
(
[0] => 1.24
[1] => 7.5
)

Each ? leaves one parameter open. A final ... leaves the remaining parameters open. PHP evaluates the supplied arguments when it creates the closure and calls the target only when you invoke that closure.

  • A parse error at ? usually means your shell selected an older PHP binary. This syntax is parsed when the file loads, even inside a version check.

Create a formatter with both the channel and severity fixed to worker and WARNING. Pass it to array_map() over two job messages and check that both lines start with WARNING [worker].

Continue with Elapsed Time with Time\Duration.