doujin8476 2011-08-27 20:23
浏览 62
已采纳

PHP静态成员没有持有值

Hi i have a strange problem with a WordPress plugin that i am writing, but this isnt about WordPress per se and more to do with PHP so please read on so I can explain. The WordPress plugin is hooked up so that the init() function gets called... this works i can confirm it gets called once.

class MyClass
{
   static $i=0;

   public static function init()
   {
     self::$i++;
   }

   public static function dosomething()
   {
     echo 'i is = ' . self::$i;
   }
}

When callinf dosomething() for the first time from within Wordpress it is ok. I then have another ajax-response.php file which includes the above class and again calls dosomething, which prints the i value = 1.

The problem is the i value when calling via the ajax-response.php script is back to 0?

Its as if it is executing in a totally different memory space and creating a new program, such that static member variables are only shared between same process as opposed to multiple web threads.

Any ideas?

Thanks in advance,

Chris

  • 写回答

4条回答 默认 最新

  • duanjian4150 2011-08-27 20:25
    关注

    Its as if it is executing in a totally different memory space and creating a new program, such that static member variables are only shared between same process as opposed to multiple web threads.`

    Exactly! :) That's 100% how this works. Each PHP request is a new one, with its own memory. The static keyword is not designed to work around that.

    If you want to persist stuff across multiple processes / requests in a web application, you need to use sessions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图