PHP 8.6 Partial Function Application: A Complete Guide with Practical Examples
Have you ever written the same arrow function again and again just because you wanted to reuse an existing PHP function with one argument already configured?
For example, imagine you have a function that calculates discounts. You want to apply a fixed discount rate to different products without writing a new anonymous function every time.
Traditionally, PHP developers use arrow functions or closures to solve this problem. But PHP 8.6 introduces something interesting: Partial Function Application.
This feature allows you to provide some function arguments in advance and leave the remaining arguments for later. PHP automatically creates a Closure that executes the original function when you provide the missing values.
The result? Less repetitive code, cleaner callbacks, and a more expressive way to work with PHP functions.
In this tutorial, you will learn how Partial Function Application works in PHP 8.6, understand the ? and ... placeholders, compare the old and new approaches, and explore practical examples you can use in real PHP projects.
What Is Partial Function Application in PHP 8.6?
Partial Function Application is a programming technique that allows you to call a function with only some of its arguments and postpone supplying the remaining arguments.
Instead of executing the original function immediately, PHP creates a new Closure containing the arguments you have already provided.
You can then call that Closure whenever you need to supply the remaining arguments.
Let's understand this with a simple example.
Suppose you have a function that adds two numbers:
<?php
function add(int $a, int $b): int
{
return $a + $b;
}
echo add(10, 5);
// Output: 15
Now imagine that you frequently need to add 10 to different numbers.
Before PHP 8.6, you could create an arrow function:
<?php
$addTen = fn(int $number): int => add(10, $number);
echo $addTen(5);
echo $addTen(20);
echo $addTen(50);
// Output:
// 15
// 30
// 60
This works perfectly, but you need to write another function to reuse the original add() function.
PHP 8.6 makes this easier with Partial Function Application:
<?php
$addTen = add(10, ?);
echo $addTen(5);
echo $addTen(20);
echo $addTen(50);
// Output:
// 15
// 30
// 60
Look closely at this line:
$addTen = add(10, ?);
What happens here?
- PHP receives the first argument,
10. - The
?placeholder indicates that the second argument will be supplied later. - PHP creates a Closure and stores it in
$addTen. - When you call
$addTen(5), PHP executes the originaladd()function with10and5.
The important point: Partial Function Application does not execute the original function immediately. It creates a reusable Closure that executes the original function when the missing arguments are provided.
Why Did PHP Introduce Partial Function Application?
PHP already supports anonymous functions, arrow functions, and first-class callable syntax. So why introduce another way to work with functions?
Consider a real development situation.
You are building an e-commerce application. You have a function that calculates product prices, applies discounts, or formats customer information.
You want to reuse these functions with certain arguments already configured.
Without Partial Function Application, you often need to write additional arrow functions:
$applyDiscount = fn($price) => calculateDiscount(10, $price);
With PHP 8.6, you can write:
$applyDiscount = calculateDiscount(10, ?);
The second approach directly communicates which argument is fixed and which argument is expected later.
This is particularly useful when working with:
- Array functions such as
array_map()andarray_filter(). - Reusable callbacks.
- String manipulation.
- Data transformation.
- Validation functions.
- Pricing calculations.
- Functional programming patterns.
Understanding the Two PHP 8.6 Placeholders
Partial Function Application introduces two important placeholder symbols:
| Placeholder | Meaning |
|---|---|
? |
Reserves exactly one argument for later. |
... |
Reserves all remaining arguments for later. |
Let's understand both with practical examples.
1. Question Mark (?) Placeholder
The ? placeholder represents exactly one argument that you want to provide later.
Consider this example:
<?php
function multiply(int $a, int $b): int
{
return $a * $b;
}
$multiplyByFive = multiply(5, ?);
echo $multiplyByFive(4);
echo $multiplyByFive(10);
echo $multiplyByFive(20);
// Output:
// 20
// 50
// 100
Here is what happens:
- The first argument is fixed at
5. - The second argument is left open using
?. - PHP creates a Closure.
- Each time you call the Closure, you provide a different second argument.
You can also leave multiple arguments open.
<?php
function calculateTotal(int $price, int $tax, int $shipping): int
{
return $price + $tax + $shipping;
}
$calculate = calculateTotal(1000, ?, ?);
echo $calculate(180, 50);
// Output: 1230
In this example, the product price is fixed at 1000. You provide the tax and shipping amounts when calling the Closure.
Remember: Every ? represents exactly one required parameter in the resulting Closure, even if the original parameter has a default value.
2. Three Dots (...) Placeholder
The ... placeholder reserves all remaining arguments that have not already been supplied.
Let's use the same calculation example:
<?php
function calculateTotal(int $price, int $tax, int $shipping): int
{
return $price + $tax + $shipping;
}
$calculateOrderTotal = calculateTotal(1000, ...);
echo $calculateOrderTotal(180, 50);
echo $calculateOrderTotal(200, 75);
// Output:
// 1230
// 1275
In this example:
- The first argument,
$price, is fixed at 1000. - The
...placeholder reserves the remaining arguments. - You provide the tax and shipping amounts later.
The ... placeholder can also be used when you want to delay a function call even though all arguments have already been supplied:
<?php
$calculate = calculateTotal(1000, 180, 50, ...);
echo $calculate();
// Output: 1230
The Closure does not require any additional arguments in this case because all original arguments are already configured.
Important: The ... placeholder can appear only once and must be the final argument. It is different from normal argument unpacking.
PHP 8.5 vs PHP 8.6: What Has Changed?
One of the easiest ways to understand a new PHP feature is to compare it with the approach developers previously used.
Let's take a practical example using array_filter().
Suppose you have an array containing different PHP version numbers, and you want to find versions greater than or equal to PHP 8.6.
Before PHP 8.6
You would normally use an arrow function:
<?php
$versions = ['8.4', '8.5', '8.6', '8.7', '9.0'];
$supportsPfa = array_filter(
$versions,
fn($version) => version_compare($version, '8.6', '>=')
);
print_r($supportsPfa);
PHP 8.6 Approach
With Partial Function Application, you can write:
<?php
$versions = ['8.4', '8.5', '8.6', '8.7', '9.0'];
$supportsPfa = array_filter(
$versions,
version_compare(?, '8.6', '>=')
);
print_r($supportsPfa);
Both approaches produce the same filtered array:
Array
(
[2] => 8.6
[3] => 8.7
[4] => 9.0
)
The PHP 8.6 version is shorter because you no longer need to write an additional arrow function.
This is particularly useful when an existing PHP function already performs the operation you need.
Practical Examples of Partial Function Application
Now let's move beyond simple mathematical operations and look at examples that demonstrate how this feature can help in everyday PHP development.
Example 1: Reusing a String Replacement Function
PHP provides the built-in str_replace() function for replacing text inside strings.
Suppose you frequently replace hello with hi.
You can configure the replacement once:
<?php
$replaceHello = str_replace('hello', 'hi', ?);
echo $replaceHello('hello world');
echo $replaceHello('hello PHP');
echo $replaceHello('hello developer');
// Output:
// hi world
// hi PHP
// hi developer
Here, the search and replacement values remain fixed. Only the input string changes.
This is a good example of creating reusable string-processing callbacks.
Example 2: Filtering Numeric Values
Imagine you receive data from an API, CSV file, or form submission.
You want to filter an array and keep only numeric values.
<?php
$values = ['10', 'hello', '25', 'PHP', '50', '100'];
$numericFilter = is_numeric(...);
$result = array_filter($values, $numericFilter);
print_r($result);
Output:
Array
(
[0] => 10
[2] => 25
[4] => 50
[5] => 100
)
Here, is_numeric(...) creates a callable using the existing function.
This particular syntax is an example of first-class callable syntax, available since PHP 8.1. It works naturally alongside Partial Function Application.
Example 3: Creating a Reusable Discount Calculator
Let's consider an e-commerce application.
You have a function that calculates the final price after applying a discount.
<?php
function calculateDiscount(float $price, float $discount): float
{
return $price - ($price * $discount / 100);
}
$applyDiscount = calculateDiscount(1000, ?);
echo $applyDiscount(10);
echo $applyDiscount(20);
echo $applyDiscount(30);
// Output:
// 900
// 800
// 700
The original price is fixed at 1000, while the discount percentage changes.
This approach can be useful when creating reusable pricing callbacks for product or order calculations.
Example 4: Using Named Placeholders
PHP 8.6 also allows you to use named arguments with placeholders.
Named arguments let you specify function parameters using their names instead of relying entirely on their position.
Consider this function:
<?php
function createUser(
string $name,
string $role,
bool $active
): array {
return [
'name' => $name,
'role' => $role,
'active' => $active,
];
}
You can configure the role and active status in advance:
<?php
$createAdmin = createUser(
role: 'admin',
active: true,
name: ?
);
print_r($createAdmin('Abdul'));
Output:
Array
(
[name] => Abdul
[role] => admin
[active] => 1
)
Notice that the name parameter is supplied later, while the other two values are already configured.
Named placeholders also allow you to control the order of the resulting Closure parameters.
For example:
<?php
$removeCharacters = str_replace(
subject: ?,
search: ?,
replace: ''
);
echo $removeCharacters('a-b-c', '-');
// Output: abc
The Closure accepts the subject first and the search string second.
This is useful when working with functions that have multiple parameters and you want to make your code easier to understand.
Partial Function Application vs Arrow Functions vs Closures
PHP developers already have several ways to create reusable functions. Understanding their differences helps you choose the right approach.
| Feature | Arrow Function | Closure | Partial Application |
|---|---|---|---|
| Syntax | fn() |
function() |
functionName(?, ...) |
| Reusable | Yes | Yes | Yes |
| Automatically captures outer variables | Yes, by value | No, explicit use required |
Not applicable in the same way |
| Preconfigures original function arguments | Manually | Manually | Yes |
| Returns a Closure | Yes | Yes | Yes |
Arrow Function Example
$addTen = fn($number) => add(10, $number);
Anonymous Function Example
$addTen = function ($number) {
return add(10, $number);
};
Partial Function Application Example
$addTen = add(10, ?);
All three approaches can achieve the same result in this example.
However, Partial Function Application is especially convenient when you already have a function and simply want to configure some of its arguments.
For more information about PHP functions, explore our PHP Functions Tutorial.
How Does Partial Function Application Work with Laravel?
If you are a Laravel developer, you already work with callbacks, collections, array transformations, and reusable functions.
Partial Function Application can make some of these operations easier to express.
For example, suppose you have a Laravel collection containing product prices:
<?php
$prices = collect([100, 200, 300, 400]);
function applyDiscount(float $price, float $discount): float
{
return $price - ($price * $discount / 100);
}
$applyTenPercentDiscount = applyDiscount(?, 10);
$discountedPrices = $prices->map($applyTenPercentDiscount);
$discountedPrices->all();
// Output:
// [90, 180, 270, 360]
Here:
- The discount percentage is fixed at 10.
- The product price is supplied later by the Collection's
map()operation. - Each collection item is processed using the same Closure.
This example demonstrates how Partial Function Application can work with Laravel collections.
You must run your Laravel application on PHP 8.6 or later to use this syntax. Also check your Laravel version and installed dependencies for PHP 8.6 compatibility before upgrading.
Important Rules and Limitations
Partial Function Application makes function calls more flexible, but there are some rules developers should understand.
1. The Question Mark Represents One Argument
Each ? placeholder reserves exactly one argument.
$calculate = calculateTotal(1000, ?, ?);
This Closure requires two arguments when called.
2. The Three Dots Placeholder Must Be Last
The ... placeholder can appear only once and must be the final argument.
Correct:
$calculate = calculateTotal(1000, ...);
Incorrect:
// Invalid syntax
$calculate = calculateTotal(..., 1000);
3. Named Arguments Must Follow Normal PHP Rules
You can use named arguments and named placeholders, but positional arguments cannot follow named arguments.
Correct:
$createUser = createUser(
role: 'admin',
active: true,
name: ?
);
4. Arguments Are Evaluated When the Closure Is Created
This is an important detail.
Consider the following example:
<?php
function getCurrentTime(): string
{
echo "Getting current time...\n";
return '12:00';
}
function greet(string $name, string $time): string
{
return "Hello $name, it is $time";
}
$greetUser = greet(?, getCurrentTime());
echo "Closure created\n";
echo $greetUser('Abdul');
The getCurrentTime() function runs when $greetUser is created, not every time the Closure is called.
This means arguments provided in advance are evaluated once and their resulting values are stored for later use.
5. Object Construction Is Not Supported
Partial Function Application cannot be used directly with object creation.
For example:
// Not supported
$object = new User(?, 'admin');
You can use a static factory method instead:
<?php
class User
{
public function __construct(
public string $name,
public string $role
) {}
public static function create(
string $name,
string $role
): self {
return new self($name, $role);
}
}
$createAdmin = User::create(?, 'admin');
$user = $createAdmin('Abdul');
Other restrictions include combining placeholders with the nullsafe operator or argument unpacking. Functions that inspect their calling scope, such as func_get_args() and compact(), are also not supported for partial application.
How to Check Your PHP Version
Before using Partial Function Application, make sure your environment supports PHP 8.6.
You can check your installed PHP version using the terminal:
php -v
Or use PHP code:
<?php
echo PHP_VERSION;
To check whether your application is running on PHP 8.6 or later:
<?php
if (version_compare(PHP_VERSION, '8.6.0', '>=')) {
echo "Partial Function Application is supported.";
} else {
echo "Please upgrade to PHP 8.6 or later.";
}
Remember that the PHP version used by your terminal may differ from the PHP version configured for your web server.
Frequently Asked Questions (FAQs)
1. What is Partial Function Application in PHP 8.6?
Partial Function Application is a PHP 8.6 feature that allows developers to provide some function arguments in advance and leave the remaining arguments for later. PHP creates a Closure that executes the original function when the remaining arguments are supplied.
2. What does the question mark (?) mean in PHP 8.6?
The ? symbol is a placeholder that reserves exactly one function argument for later. When the returned Closure is called, you must provide a value for that placeholder.
3. What does the three dots (...) mean in PHP 8.6?
The ... placeholder reserves all remaining arguments that have not already been provided. It must appear only once and at the end of the argument list.
4. Does Partial Function Application return a Closure?
Yes. PHP creates a Closure when you use Partial Function Application. The Closure stores the arguments already provided and accepts the remaining arguments when called.
5. Is Partial Function Application available in PHP 8.5?
No. Partial Function Application is introduced in PHP 8.6. Applications running PHP 8.5 or older cannot use this syntax.
6. What is the difference between Partial Function Application and an arrow function?
An arrow function allows you to write a short anonymous function. Partial Function Application allows you to reuse an existing function by providing some arguments in advance. Both can produce similar results, but Partial Function Application requires less code for this particular use case.
7. Can I use Partial Function Application with array_map() and array_filter()?
Yes. You can create a Closure using Partial Function Application and pass it as a callback to PHP functions such as array_map() and array_filter().
8. Can Partial Function Application be used in Laravel?
Yes. Laravel applications running on PHP 8.6 or later can use Partial Function Application wherever compatible function calls and Closures are accepted. Make sure your framework version and dependencies support the selected PHP version.
9. Are PHP 8.6 placeholders the same as variadic arguments?
No. A ? placeholder reserves exactly one argument, while ... in Partial Function Application reserves the remaining arguments. Regular variadic parameters use ...$arguments in a function declaration to collect multiple arguments into an array. They are related concepts but serve different purposes.
10. Should I replace all arrow functions with Partial Function Application?
No. Partial Function Application is useful when you want to reuse an existing function with some arguments already configured. Arrow functions remain useful when you need custom logic, calculations, or expressions that are not already available in an existing function.
Conclusion
Partial Function Application is a useful addition to PHP 8.6 that makes working with reusable functions and callbacks easier.
Instead of writing additional arrow functions every time you want to configure an existing function, you can use the ? and ... placeholders to provide arguments in advance.
The biggest advantage is cleaner and more expressive code, especially when working with array operations, string processing, data transformations, and reusable business logic.
If you are learning modern PHP or building applications with Laravel, understanding Partial Function Application will help you take advantage of the latest PHP language improvements.
Keep learning and improving your PHP skills with Online Learner's PHP Tutorial. Explore more examples, understand PHP functions, and build your programming knowledge step by step.
Further Reading
- PHP Tutorial – Learn PHP from Basics to Advanced
- PHP Functions – Learn How Functions Work in PHP
- PHP and MySQL Functions – Practical Database Programming
- Official PHP 8.6 Release Announcement
- PHP Partial Function Application Documentation
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts.
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
