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.

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

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c