PHP
OPcache configuration
Learn to boost performance by keeping PHP bytecode in memory with OPcache.
What does OPcache do?
OPcache stores the compiled bytecode of PHP scripts in memory, removing the cost of recompiling on every request. On the first request PHP compiles your file to bytecode and writes it to shared memory.
Later requests read straight from memory, not from source. This gives a visible speed-up, especially with large frameworks.
OPcache is on by default except in CLI; you control it with opcache.enable in php.ini. You read memory and hit statistics with opcache_get_status, and clear the cache with opcache_reset.
opcache_get_status and opcache_reset
opcache_get_status takes one argument: pass true for the full listing (every script), false for summary only. If OPcache is disabled the call returns false, so it is safe to check function_exists first.
opcache_reset clears the whole cache and returns true; you typically call it when deploying fresh code or during tests. Calling it often in production adds recompilation cost on the next requests.
Exercise Report OPcache extension availability
Check 'opcache_get_status' with function_exists, assign to $loaded. Likewise check 'opcache_reset', assign to $can_reset. Print each as 1 or 0 with echo.
Show example solution
function_exists('opcache_get_status') returns true/false. Assign it to $loaded and print 1/0 with a ternary. Do the same for opcache_reset.
Example solution:
<?php
$loaded = function_exists('opcache_get_status');
$can_reset = function_exists('opcache_reset');
echo ($loaded ? "1\n" : "0\n");
echo ($can_reset ? "1\n" : "0\n");
Test yourself
-
What does opcache_get_status return?
- Only memory usage in bytes
- An array with OPcache statistics, or false
- Opens a new OPcache session
- Recompiles the PHP files
Show answer
An array with OPcache statistics, or false — Correct. It returns statistics as an array; false when OPcache is off.
-
Complete the opcache_get_status call
$status = ____(false);
if ($status === false) {
echo "OPcache disabled\n";
}
Show answer
$status = opcache_get_status(false);
if ($status === false) {
echo "OPcache disabled\n";
}
-
Match the OPcache concepts
- opcache_get_status
- Reads statistics
- opcache_reset
- Clears the cache
- opcache.enable
- php.ini setting
- bytecode
- Compiled script
Next lesson: Profiling tools