In Java, a static member maintains its value for all instances of the class. Can this be done in PHP? I remember hitting this issue a few years ago and my current test confirms that static member does not maintain its state. So I guess, in PHP a class is unloaded and all its state destroyed after each request.
index.php
include('cache.php');
$entityId=date('s');
$uri='page'.$entityId;
$cache = new Cache();
$cache->cacheUrl($uri, $entityId);
cache.php
class Cache {
private static $URL_CACHE;
public function cacheUrl($url, $entityId) {
echo '<br>caching '.$url.' as '.$entityId;
$URL_CACHE[$url]=$entityId;
echo '<br>Cache content:<br>';
foreach ($URL_CACHE as $key => $value) {
echo 'Key: '.$key.' Value: '.$value.'<br>';
}
}
}
Output (each time I get a single Key=>Value)
caching test33 as 33
Cache content:
Key: test33 Value: 33
I understand we do not have the concept of a JVM in PHP. Is there still a way to do this in a standard installation of PHP (typical VPS hosting service with a cPanel)?
During script execution all instances of class have access to static variable and can change it.
Here's a test (note self::
when acessing $URL_CACHE
):
class Cache {
private static $URL_CACHE;
public function cacheUrl($url, $entityId) {
echo '<br>caching '.$url.' as '.$entityId . '<br />';
self::$URL_CACHE[$url]=$entityId;
echo '<br>Cache content:<br>';
foreach (self::$URL_CACHE as $key => $value) {
echo 'Key: '.$key.' Value: '.$value.'<br />';
}
}
}
$cache = new Cache();
$cache->cacheUrl('uri1', 'ent1');
$ya_cache = new Cache();
$ya_cache->cacheUrl('uri2', 'ent2');
Output is similar to:
<br>caching uri1 as ent1<br />
<br>Cache content:<br>Key: uri1 Value: ent1<br />
<br>caching uri2 as ent2<br />
<br>Cache content:<br>Key: uri1 Value: ent1
<br />Key: uri2 Value: ent2<br />
Code on eval: https://3v4l.org/WF4QA
But if you want to store self::$URLS_CACHE
between script executions - use storages like databases, files, key-value storages, whatever.