Navigation

Php

How to Use PHP's First-class Callable Syntax

Discover PHP 8.1's cleaner way to create callable references without using strings or arrays - making your functional programming more readable.

Table Of Contents

Here's How

The issue is that traditional callable syntax with strings and arrays is verbose and error-prone. You can solve this by using the ... syntax:

<?php

class Calculator {
    public function add(int $a, int $b): int {
        return $a + $b;
    }
    
    public static function multiply(int $a, int $b): int {
        return $a * $b;
    }
}

function processNumber(int $num): int {
    return $num * 2;
}

// ❌ Old way - strings and arrays
$oldCallables = [
    'processNumber',                    // Function as string
    ['Calculator', 'multiply'],         // Static method as array
    [new Calculator(), 'add'],          // Instance method as array
];

// ✅ New way - first-class callable syntax
$newCallables = [
    processNumber(...),                 // Clean function reference
    Calculator::multiply(...),          // Clean static method reference
    (new Calculator())->add(...),       // Clean instance method reference
];

// Usage examples
$numbers = [1, 2, 3, 4, 5];

// Map with function reference
$doubled = array_map(processNumber(...), $numbers);
// Result: [2, 4, 6, 8, 10]

// Filter with method reference
$calc = new Calculator();
$filtered = array_filter($numbers, fn($n) => $calc->add($n, 5) > 7);

// Create reusable callable variables
$multiplyBy = Calculator::multiply(...);
$result = $multiplyBy(6, 7); // 42

// Pass callables around
function executeOperation(callable $operation, int $a, int $b): int {
    return $operation($a, $b);
}

echo executeOperation(Calculator::multiply(...), 8, 9); // 72

Key Points

First-class callable syntax provides several advantages:

  1. No String Errors: IDE can validate method/function names at write time
  2. Refactoring Safe: Automatic updates when renaming methods
  3. Better Performance: No runtime string parsing
  4. Cleaner Code: More readable than array syntax

Common Patterns:

  • functionName(...) for functions
  • ClassName::methodName(...) for static methods
  • $object->methodName(...) for instance methods
  • Works with array functions like array_map, array_filter

This syntax makes functional programming in PHP much more elegant and maintainable.

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Php