Skip to content

Did you know?

In PHP 8.6, a ? in a function call creates a new callable instead of calling the function.

str_replace(' ', '-', ?) returns a function that slugs any string, ready for array_map() or the |> pipe.

  • Web servers
  • Applies to PHP 8.6 and later
  • Last checked

Explained

PHP 8.6 adds partial function application. When you write ? in place of an argument, PHP doesn’t call the function. It returns a new callable that waits for the missing argument. ... stands for all remaining arguments.

$toSlug = str_replace(' ', '-', ?);

echo $toSlug('hello php world');                // hello-php-world
$slugs = array_map($toSlug, ['a b', 'c d']);    // ['a-b', 'c-d']

It pairs especially well with the pipe operator from PHP 8.5, where every step must be a one-argument callable. Before 8.6 you needed an arrow function for any step with extra arguments:

$slug = $title
    |> trim(...)
    |> strtolower(...)
    |> str_replace(' ', '-', ?);

Arguments you do pass are evaluated once, when the callable is created, not on every call. new can’t be partially applied, but static factory methods can.

Learn more

← All tech tips · Suggest a fix

Back to top