All posts
Published in PHP

How PHP works internally?

Profile image of Atakan Demircioğlu
By Atakan Demircioğlu
Fullstack Developer

php-works-internally

Here are my notes about how PHP works internally. If you guys have any additions please add your comments as a response.

Firstly, What is PHP?

  • PHP (Hypertext Preprocessor) is an open-source general-purpose scripting language that is especially suited for web development and can be embedded into HTML.
  • Written in C

How works PHP internally?

  • Zend Engine is the internal compiler and runtime engine for PHP
  • PHP isolates every execution. No shared memory or shared resources among the executions.
  • There are a few main steps that explain how PHP works internally.
  • These steps are (Tokenizing, Parsing, and Compiling)

Tokenizing: In this step, the PHP interpreter takes the PHP codes and builds a set of understandable units called tokens.

For example;

<?php
echo "Hello world";

This will convert to

<?php to T_OPEN_TAG
echo to T_ECHO
"Hello world" to T_CONSTANT_ENCAPSED_STRING

Here is the list of all parser tokens.

Parsed tokens are organized in a tree structure and this structure is named AST (Abstract syntax tree).

AST (Abstract syntax tree): AST, is a tree representation of the source code of a computer program that conveys the structure of the source code. Each node in the tree represents a construct occurring in the source code.

For example

<?php
echo 5+5;
This AST will look like this;
operation => ECHO,
operand => expression (
    operation => ADD,
    operand1 => 5,
    operand2 => 5
)

PHP is then able to compile this tree into an intermediate representation called Opcode.

The Opcode is what is actually executed by the virtual machine.

How PHP works internally? image 1

Another good flow to understand how PHP works.

How PHP works internally? image 2

In this image, you can see the OpCode cache. If you understand how PHP works, know you know that is a big bottleneck for every request. Because in every request you are making the same things.

Having a fresh execution in every request doesn’t a performance thing if we have to compile PHP syntax into opcode every single time.

So that is why the Opcache comes in this picture.

If you send a request to x.php PHP parses then compiles, and then executes. The second time PHP directly fetches from the opcode cache and executes it.

In another article, we will cover PHP-FPM and also PHP 8 JIT.

References