Working of PHP OpCache

Caching and execution of PHP OpCode

In computer science, OpCode is Operation Code which according to Wikipedia is the portion of a machine language instruction that specifies the operation to be performed. Since PHP is an interpreted language, each time a request is made to the PHP application or the PHP script is run via the terminal the code gets executed line by line. The PHP script is compiled down to an intermediate bytecode which is then interpreted by the runtime engine.

While being interpreted it gets compiled to an intermediate language OpCode (think of it as a specialized assembly) and runs on a virtual machine (this is the Zend Engine). The output is generated and sent to the client or printed on the terminal. You can see a normal request without opcache below...

Now, once you enable the opcache, for the first request the OpCode is cached into the memory and then served to the virtual machine (VM). Thus adding an extra step to the request-response cycle. Keep in mind, this is only for the first request and not for the first request from each user.

After the first request, for the next consecutive requests, we already have the OpCode in the memory thus the VM directly uses this and generates the required output and sends it to the client. Depending on your configuration, you might have to restart your server if the source code changes, else the changes will not be reflected in the output.

Check out Configure PHP OpCache to Improve Speed, for further detail on how to configure the opcache for your server.