Re: Automatically execute Closures returned from primary script

From: Date: Tue, 22 Sep 2026 15:21:53 +0000
Subject: Re: Automatically execute Closures returned from primary script
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-132592@lists.php.net to get a copy of this message
On Tue, 22 Sept 2026 at 14:19, Tim Düsterhus <tim@bastelstu.be> wrote: > > 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 Hi Tim, A BIG yes from me. I currently tend to use the following pattern in executable scripts, or even index.php files in web applications: ```php (static function (): void { // This is the main entry point. })(); ``` For example: https://github.com/carthage-software/mago/blob/main/composer/bin/mago#L18 It works, but I think returning the closure is cleaner and communicates the intent more clearly: Just to confirm my understanding: when the file is included from another script, the closure would still be returned without being executed, so the following would continue to work as it does today: ```php $callable = require 'script_file.php'; $callable(); ``` Is that correct? Best regards, Seifeddine

« previous php.internals (#132592) next »