PHP源码/PHP内核主入口点在哪?PHP程序执行核心入口代码是什么?
Great question! Since PHP is designed to work with a variety of servers (via its SAPI layer, as you noted with the CLI "mini-server"), there isn't a single global "main function"—instead, each SAPI (Server Application Programming Interface) has its own entry point that triggers the core PHP execution pipeline. Let's break this down:
1. Per-SAPI Entry Points
Each deployment mode (CLI, FPM, Apache mod_php, etc.) has its own dedicated entry function in the source code:
- CLI SAPI: The entry is the
main()function inmain/php_cli.c. This is what runs when you typephp script.phpin your terminal—it handles command-line arguments, initializes the PHP environment, and kicks off the request processing. - FPM SAPI: For FastCGI Process Manager, the entry is the
main()function insapi/fpm/fpm/fpm_main.c. This manages worker processes and handles incoming FastCGI requests from web servers like Nginx. - Apache mod_php: The startup entry is
php_apache2_startup()insapi/apache2handler/sapi_apache2.c, which hooks into Apache's request cycle to trigger PHP execution for each web request.
2. Core Execution Pipeline (Shared Across All SAPIs)
No matter which SAPI you're using, they all delegate to PHP's core lifecycle functions (which you mentioned: minit, rinit, etc.) to execute scripts:
- Module Initialization (minit): Triggered once per process via
php_module_startup(). This initializes all loaded PHP extensions (like mysqli, json) and sets up global runtime state. - Request Initialization (rinit): Triggered per request via
php_request_startup(). This resets request-specific state (like superglobals$_GET,$_POST), activates the Zend Engine, and prepares for script execution. - Script Execution: The actual interpretation and execution of PHP code happens via
zend_execute_scripts(), which parses the script into opcodes and runs them through the Zend Engine's executor. - Request Shutdown (rshutdown): Cleanup per-request resources via
php_request_shutdown()—this includes closing database connections, freeing memory tied to the request, and executing shutdown functions registered withregister_shutdown_function(). - Module Shutdown (mshutdown): Triggered once per process when it exits via
php_module_shutdown(), cleaning up global extension resources.
Key Takeaway
The "entry point" for PHP execution depends on how you're running it (your SAPI), but all paths converge on the core Zend Engine and lifecycle functions to parse, compile, and execute your PHP code.
内容的提问来源于stack exchange,提问作者Alana Storm

