WordPress.org

Ready to get started?Download WordPress

Forums

PHP static member not holding value (2 posts)

  1. g18c
    Member
    Posted 2 years ago #

    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

  2. adrian7
    Member
    Posted 2 years ago #

    That's right because anytime you load a php page, the object(s) will re-create, as you load it for the first time.
    You can't store something in a static var and then expect to be available later when re-loading the page - PHP is different from Java/JSP.

    You have to use $_SESSION for that.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.