Invokes a callback and passes the supplied arguments.
What Is call_user_func() in PHP?
Invokes a callback and passes the supplied arguments.
Its syntax is:
call_user_func(callable $callback, mixed ...$args): mixed
Parameters:
$callback— Accepted as callable; required argument.$args— Accepted as mixed ...; required argument.
Return type: mixed. The callback must be callable and its arguments must match the target signature.
Availability: Core PHP.
Example 1: Basic Usage
<?php
echo call_user_func("strtoupper", "hello");
Output:
HELLO
The callback must be callable and its arguments must match the target signature.
Example 2: A Different Input
<?php
echo call_user_func(fn($number) => $number * 2, 7);
Output:
14
The callback must be callable and its arguments must match the target signature.
Practical Example: Applying It in a Program
<?php
$formatPrice = fn($amount) => number_format($amount, 2); foreach ([12.5, 8, 30] as $price) { echo call_user_func($formatPrice, $price) . PHP_EOL; }
Output:
12.50
8.00
30.00
The callback must be callable and its arguments must match the target signature.
Important Behavior and Edge Cases
- Key behavior: The callback must be callable and its arguments must match the target signature.
- Environment: Core PHP.
Comparison With Related Functions
| Function | Purpose |
|---|---|
call_user_func() | Invokes a callback and passes the supplied arguments. |
call_user_func_array() | call_user_func_array() takes callback arguments in one array; call_user_func() takes them as separate arguments. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring this behavior: The callback must be callable and its arguments must match the target signature | The callback must be callable and its arguments must match the target signature. |
Key Takeaways
- Invokes a callback and passes the supplied arguments.
- The callback must be callable and its arguments must match the target signature.
- Core PHP.
Summary: The callback must be callable and its arguments must match the target signature.