How does PHP work internally?

What is PHP?

PHP is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.

How does PHP script work internally?

When you write php code there are different stages that it has to go through in order to take php syntax and convert that to html as an output.

PHP script has following stages:

Lexing/Tokenizing:

PHP interpreter first take php code and builds set of tokens.

Parsing:

PHP interpreter then checks to see if the script matches the syntax rules and uses tokens to build an Abstract Syntax Tree (AST).

Compilation:

Next step, PHP interpreter takes AST tree and it translates AST nodes into low-level Zend opcodes.

Interpretation:

Finally, these opcodes are then run on Zend Engine (ZE) VM. The output is pretty much whatever your PHP script outputs via commands such as echoprintvar_dump, and so on as a text on either console or on a browser.

How can you improve PHP execution?

Now, that you know how php works internally. PHP is an interpreted language which means, when a PHP script runs, the interpreter parses, compiles, and executes the code over and over again on each request.

It means it wastes too much CPU resources because it has to start over and over on every request.

OPcache improves PHP performance by storing precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request.

Now, if you look at the process again it works differently when using OpCache.

  • When php script is executed it asks to see if we have cached copy of opcodes
  • If we do it straightly goes to execution step and skips following steps:
    • Lexing
    • Parsing

Therefore, you will see some performance boost when using OpCache.