PHP 8.0 allows named arguments, which bind values by formal parameter names rather than position.
What It Does
PHP 8.0 allows named arguments, which bind values by formal parameter names rather than position. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.0 or later.
PHP 8.0 introduced union types, named arguments, match, nullsafe access and several behavior changes. Test syntax against the intended runtime.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Start with the smallest meaningful working case.
<?php
function limitPage(int $page, int $size = 20): int { return ($page - 1) * $size; }
echo limitPage(size: 10, page: 3);
Example 2: Another Case
Examine the edge case and the observable result.
<?php
function fetchSlice(int $offset, int $limit): string { return "$offset:$limit"; }
try { echo fetchSlice(start: 0, limit: 20); } catch (Error $e) { echo 'Renamed parameter breaks named callers'; }
Practical Example: Putting It to Use
Apply the technique to a small practical task.
<?php
function mailEnvelope(string $to, string $subject = 'Hello'): array { return compact('to', 'subject'); }
print_r(mailEnvelope(to: '[email protected]'));
// Public parameter names are part of your named-argument API.
Important Behavior and Edge Cases
Renaming parameters in a public function can break named callers even if positional calls still work.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| 8.0 Named Arguments and Backward Compatibility | PHP 8.0 allows named arguments, which bind values by formal parameter names rather than position. |
| Related approach | Use named arguments for clarity but treat public parameter names as part of compatibility. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for 8.0 Named Arguments and Backward Compatibility | Renaming parameters in a public function can break named callers even if positional calls still work. |
| Assuming a related mechanism has the same behavior | Use named arguments for clarity but treat public parameter names as part of compatibility. |
Key Takeaways
- PHP 8.0 allows named arguments, which bind values by formal parameter names rather than position.
- Renaming parameters in a public function can break named callers even if positional calls still work.
- Use named arguments for clarity but treat public parameter names as part of compatibility.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.