PHP 8 Intermediate Language Basics · 6 min read

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

Syntax
array_map(strlen(...), $titles);

Example

src/Lengths.php
<?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

  1. strlen(...) is a callable for array_map.
  2. The titles ab and cdef become lengths 2 and 4.
  3. slug is an instance method.
  4. slug(...) binds that instance.
  5. The closure lowercases and replaces spaces.
  6. The echo prints intro-routes.
  7. A misspelled function in (...) is a compile-time style error when the function is unknown.
  8. 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.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…