First-class callable syntax creates a Closure; it does not call the target immediately. When the callback name comes from configuration, validate it before conversion and report a controlled application error instead of relying on the engine’s exact message for a missing function.
Last updated: November 22, 2026.
<?php
function resolveCallback(string $name): Closure
{
$allowed = ['strlen', 'trim', 'strtolower'];
if (!in_array($name, $allowed, true) || !is_callable($name)) {
throw new BadFunctionCallException(
sprintf('Configured callback "%s" is not available.', $name)
);
}
return Closure::fromCallable($name);
}
$callback = resolveCallback('strlen');
echo $callback('WebCheatSheet');The allowlist prevents an untrusted configuration value from selecting any callable visible to PHP. Use a registry of application-owned callbacks for larger systems, and log the configuration key rather than exposing internal function names to end users.
Choose syntax based on where the callback comes from
For a known function written directly in code, PHP’s first-class callable syntax is concise: $callback = strlen(...);. It was introduced in PHP 8.1 and creates a Closure while preserving the scope at which the callable is acquired.
A string loaded from configuration is different. PHP cannot use the literal-function form when the name is dynamic, and a typo or unavailable extension can make the target non-callable. The is_callable() function checks the value in the current scope. Closure::fromCallable() then provides an explicit conversion after the application’s allowlist and availability checks.
Do not build logic around one fatal-error message
A current PHP engine issue points out that a missing function used with first-class callable syntax can produce wording that sounds like the function was invoked. That wording is diagnostic text, not a stable control-flow interface. PHP’s Closure::fromCallable() documentation specifies that an invalid callable causes TypeError; applications should use validation and exceptions they own rather than parsing engine messages.
Catch BadFunctionCallException at the configuration or job boundary and show a generic operational error. Do not catch every Throwable around the callback invocation, because that can hide a real failure thrown by valid callback code. Revalidate after deployments that add or remove extensions, and cover missing, disallowed and valid callbacks in automated tests.