-
Notifications
You must be signed in to change notification settings - Fork 7.9k
Closed
Labels
Description
Description
Javascript support naming anonymous functions, letting the function refer to itself for recursion without polluting the surrounding scope. And it provides better stack traces. For example:
function f(cb) {
console.log(cb.name); // Output: "funName"
cb(0);
}
f(function funName(i) {
// funName is available here
if (i < 3) {
console.log(i);
funName(i + 1);
}
});
// funName is not available here.
outputting
funName
0
1
2
Would be nice if PHP could support it too. Like
function d(callable $arg) {
$ref = new ReflectionFunction($arg);
$name = $ref->getName();
var_dump($name);
$arg(0);
}
d(function funName(int $i) {
if ($i < 3) {
echo $i, "\n";
funName($i + 1);
}
});
// funName is not available here.
printing
string(7) "funName"
0
1
2
Benefits:
- Simplified Recursion: Enables recursive anonymous functions without needing workarounds like use (&$funName) or relying on debug_backtrace() hacks.
- Improved Debugging: Stack traces and error messages involving anonymous functions could show meaningful names instead of just "{closure}"
- Enhanced Metadata Support: When exporting function metadata (for instance, in APIs like OpenAI's ChatGPT tools API), a named anonymous function's name could be deduced automatically via reflection, rather than having to explicitly specify "string $functionName" (already possible if anonymous functions are simply not supported, though)
theodorejb