# PHP OPCache

OPCache is a bytecode cache for PHP. It 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.

OPCache is part of PHP's core and is included with PHP 5.5 and later.

## How OPCache Works

When a PHP script is executed, it goes through several stages:
1.  **Parsing:** The script is read and parsed into an Abstract Syntax Tree (AST).
2.  **Compilation:** The AST is compiled into Zend Opcodes.
3.  **Execution:** The Zend Engine executes the opcodes.

OPCache works by caching the opcodes from the compilation stage. When a script is requested, OPCache checks if the script has been modified. If not, it provides the opcodes from the cache, skipping the parsing and compilation stages.

## Enabling OPCache

OPCache is enabled by default in most modern PHP installations. You can verify this in your `php.ini` file.

```ini
zend_extension=opcache.so ; (or .dll on Windows)
opcache.enable=1
opcache.memory_consumption=128 ; in megabytes
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.revalidate_freq=2 ; in seconds, how often to check for file changes
opcache.fast_shutdown=1
```

## Preloading

PHP 7.4 introduced preloading to OPCache. Preloading allows you to load a set of PHP files into memory at server startup. These files are then available to all subsequent requests without having to be loaded and compiled again. This is particularly useful for frameworks, as the framework's core files can be preloaded.

To use preloading, you need to specify a PHP script in your `php.ini` file that will be executed at server startup.

```ini
opcache.preload=/path/to/your/preload.php
```

The `preload.php` script would look something like this:

```php
<?php
// preload.php
opcache_compile_file('MyClass.php');
opcache_compile_file('MyOtherClass.php');
// etc...
?>
```

Preloading provides a significant performance boost, but it comes with a trade-off: if you change any of the preloaded files, you have to restart the PHP server for the changes to take effect.
