2016-09-17 127 views
0

在Java中,静态成员为类的所有实例维护其值。这可以在PHP中完成吗?我记得几年前遇到这个问题,我目前的测试证实静态成员不会保持其状态。所以我猜,在PHP中,一个类会被卸载,并且在每次请求后它的所有状态都会被销毁。如何在PHP类中维护静态成员状态?

的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>'; 
     } 
    } 

} 

输出(每次我得到一个单一的密钥=>值)

caching test33 as 33 
Cache content: 
Key: test33 Value: 33 

我明白我们没有PHP中JVM的概念。在PHP的标准安装(使用cPanel的典型VPS托管服务)中是否还有办法做到这一点?

+0

PHP类没有编译和持久化,这是存储介质的用途。 – Blake

+0

'$ URL_CACHE'和'self :: $ URL_CACHE'是__different__变量。 –

+0

我在两个地方尝试了self :: $ URL_CACHE和Cache :: $ URL_CACHE,但没有运气。 – jacekn

回答

0

在脚本执行过程中,类的所有实例都可以访问静态变量并可以对其进行更改。

这是一个测试(注意:self:: 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'); 

输出类似于:

<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 /> 

守则EVAL:https://3v4l.org/WF4QA

但是,如果你想存储self::$URLS_CACHE脚本执行 - 使用stor像数据库,文件,键值存储等等。