Automatically execute Closures returned from primary script
| From: | Tim Düsterhus | Date: | Tue, 22 Sep 2026 13:17:51 +0000 |
| Subject: | Automatically execute Closures returned from primary script | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-132587@lists.php.net to get a copy of this message | ||
Hi
this thread concerns my PR carrying the same title as this email: https://github.com/php/php-src/pull/23658, where Gina requested that I ask the mailing list for opinions and/or objections against the feature.
My goal is to enable PHP scripts to act both as “reusable module” (defining classes or functions for use in an application) as well as an executable script at the same time, similarly to Python’s `if __name__ == "__main__"` pattern.
My current PR automatically executes any
Closure returned by the main PHP script, such that:
<?php
function my_json_decode(string $json): mixed {
return json_decode($json, flags: JSON_THROW_ON_ERROR);
}
return static function () {
var_dump(my_json_decode(file_get_contents('php://stdin')));
};
would just define my_json_decode() when included in an existing script, but print the decoding of the standard input when run as `echo '{"foo": "bar"}' |php my_json_decode.php` by executing the returned Closure, similar to echo '{"foo": "bar"}' |python3 -m json.tool.
Another possible solution, that I didn't yet evaluate, might be defining a magic constant __MAIN__ that is equivalent to __FILE__ of the script that is executed first.
Best regards
Tim Düsterhus