dongyi5070 2016-09-17 20:37
浏览 49
已采纳

如何在PHP类中维护静态成员状态?

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)?

  • 写回答

1条回答 默认 最新

  • dongxianghuan3587 2016-09-17 20:49
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播