01: Partial Function Application
Overview
Section titled “Overview”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.
Prerequisites
Section titled “Prerequisites”- PHP 8.6 CLI. Confirm the version with
php --version.
Allow about 10 minutes for the walkthrough and exercise.
What You’ll Build
Section titled “What You’ll Build”A runnable partial-function-application.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/01-partial-function-application/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));Expected Result
Section titled “Expected Result”INFO [worker] Job startedERROR [billing] Payment declinedArray( [0] => 1.24 [1] => 7.5)Why It Works
Section titled “Why It Works”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.
Troubleshooting
Section titled “Troubleshooting”- 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.
Exercise
Section titled “Exercise”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].
Wrap-up
Section titled “Wrap-up”Continue with Elapsed Time with Time\Duration.