2016-09-17 56 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像數據庫,文件,鍵值存儲等等。