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

Reply via email to