when to use static?

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

Threaded View

I started out writing a class wrapper for 3DES encryption called TDES.  
It seemed logical to declare encrypt() and decrypt() methods as static,  
so I can just call, e.g., TDES::encrypt("plaintext") without creating an  
object.  Then I wrote a class for outputting html (htmlhead() htmlfoot()  
htmlform() etc.) and once again I find myself just using static functions  
b/c they made sense there too.  Now I'm writing a wrapper for SoapClient  
and again I'm making call() and setCookie() and variousotherthings()  
methods static.  Is this idiotic?  Do I need help?  When is it proper to  
use static?

Related questions:

1) If I have a static variable, the scope is only for that http request,  
correct?  Other invocations of the script will have a different copy of  
the variable?  (I'm not creating several objects of the same class in my  

2) how do I initialize a static variable when I need to do more than just  
set it to some constant expression.  Right now I do this

class myclass {
        private static myvar;
        public static init() {
                myclass::myvar = // whatever


Slightly inelegant.

Re: when to use static?

Quoted text here. Click to load it

Use static when the method doesn't need access to object variables and
methods.  Put simply, if you need to use $this in a method, then it
the method shouldn't be static.

Quoted text here. Click to load it

You're correct.  This is a point of confusion for many people coming
from an ASP environment where (I'm pretty sure) static is static
across the entire application.  In general, requests to PHP scripts
"stand alone."

Quoted text here. Click to load it

Something similar to what you've done here.  Make the variable itself
private or protected, then have a public getter (just like object
methods and properties).  Something like this:

class Foo {
    protected static $bar = false;

    protected static loadBar() {
        self::$bar = 42;

    public static function getBar() {
        if(self::$bar === false)

        return self::$bar;

Site Timeline