Search code examples
phpphp-internals

Does PHP interpreter compiles to bytecode every command during the reading?


Could you please clarify, PHP interpreter compiles to bytecode every command and then executes or it first reads all commands and then compiles and executes them?


Solution

  • The short answer is that PHP needs to parse the whole file in order to execute it cleanly, without syntactic errors in it.

    An opcode cache (if installed as a Zend extension), can cache the opcodes by replacing the original function to compile a file and execute it only when necessary.

    Start exploring from http://lxr.php.net/xref/PHP_5_6/Zend/zend_compile.h line 675 if you would like to know the whole story.

    The reason it's all or nothing it's because if a script has syntactic errors and it's already been halfway executed, then it's impossible to undo any damage it may have caused (it's not possible to undo a network communication for instance).

    The reason it's on a per-file basis though (and not all or nothing) is for optimisations, since includes and requires can be conditional, not to mention autoloading.