PHP First-class Callables
Lesson 41 of 43 in the PHP 8 learning path.
How do I pass a function to array_map without a string name?
The (...) syntax turns a function or method into a Closure.
A string callable is not checked until it runs. A first-class callable fails earlier when the name is wrong.
Syntax & Parameters
array_map(strlen(...), $titles);
Example
<?php
declare(strict_types=1);
function lengths(array $titles): array
{
return array_map(strlen(...), $titles);
}
final class Slugs
{
public function slug(string $title): string
{
return strtolower(str_replace(' ', '-', $title));
}
}
$slugs = new Slugs();
$make = $slugs->slug(...);
echo $make('Intro routes'), PHP_EOL;
echo implode(',', lengths(['ab', 'cdef'])), PHP_EOL;
Expected Output
intro-routes 2,4
Line-by-Line Walkthrough
- strlen(...) is a callable for array_map.
- The titles ab and cdef become lengths 2 and 4.
- slug is an instance method.
- slug(...) binds that instance.
- The closure lowercases and replaces spaces.
- The echo prints intro-routes.
- A misspelled function in (...) is a compile-time style error when the function is unknown.
- Do not build callables from user strings.
Common Pitfalls & Security
Know the failure before you copy it.
- A string from a request used as a callable is remote code selection. Do not do it.
- The (...) form still calls the real function. It is not a sandbox.
- Static methods need ClassName::method(...).
- Forgetting the instance makes a non-static method call fail.
Best Practices & Modern Standards
Prefer function(...) over a string name in array_map and usort.
Keep the callable pointing at your own code, never at a name taken from input.
Real-World Use
A title list is measured with strlen(...) and slugged with a bound method, without a quoted function name.
Frequently Asked Questions
Is this the same as a closure?
It creates a Closure that forwards to the named callable.
Can I pass arguments in the (...)?
No. The parentheses stay empty. Arguments are supplied when the closure is called.
Does this work for methods?
Yes. $object->method(...) binds the object.
Why not a string?
A string is not verified until call time and is unsafe if the string comes from a user.