In PHP, how do I cache strings with examples?

In PHP, you can cache strings using various methods like APCu, file caching, or even using a simple array. Below is an example using a simple file caching technique.

<?php function cacheString($key, $value, $expiry = 3600) { $cacheFile = '/path/to/cache/' . md5($key) . '.cache'; if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $expiry) { // Return cached value return file_get_contents($cacheFile); } else { // Store new value in cache file_put_contents($cacheFile, $value); return $value; } } // Usage $cachedString = cacheString('greeting', 'Hello, World!'); echo $cachedString; // This will either fetch from cache or store 'Hello, World!' ?>

PHP caching string caching file caching APCu caching techniques