php 5: Static class variables

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hi folks!

I noticed in my static example which I did in PHP that the static
variable is not stored over multiple php pages. So this does differ
than to other OO languages like JSP. Is this so or did I something

 class MyClass
    static $MyVar = 123;
    function getMyVar()
    { return MyClass::$MyVar; }

1. Call on my server
    // set here the value
    MyClass::$MyVar = 456;

    echo MyClass::$MyVar;  // prints 456

    myInst1 = new MyClass();
    echo myInst1->getMyVar();  // prints 456


2. Call on my server
    myInst2 = new MyClass();
    echo myInst2->getMyVar();  // prints 123 ??? Expected was 456


Mark Egloff

Re: php 5: Static class variables

joes wrote:

Quoted text here. Click to load it

Ahem ... JSP is not directly an object oriented language. Java, on
which JSP is founded, is object oriented, though.

Quoted text here. Click to load it

It is indeed the case that static variables behave differently in PHP
compared to Java. In the case of Java Servlets and/or JSP all the HTTP
requests are (generally) served by one Java Virtual Machine. Thus,
static variables of classes just exist once on a server and do not have
any notion of HTTP requests.

In PHP though, the PHP environment is newly created for each HTTP
request. Without further measures, the PHP scripts are even recompiled
for each request. So, static class variables are deleted after a
request has been completed.

You should note that in Java static variables are not only common to
the requests of a single session, but to all requests that arrive on
the server. Thus, you should think twice (better even more) before
using static variables in a JSP or Servlet environment. The most common
use case for static variables in these contexts is resource sharing
between the requests. One example for that is the Struts configuration.



Re: php 5: Static class variables


I know the java environment very well. acting as at teacher and sun
certified architect, but I am very new on PHP.


Site Timeline