|
Posted by ZeldorBlat on 04/04/07 19:01
On Apr 4, 1:33 pm, darius <n...@here.invalid> wrote:
> Hi
>
> 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?
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.
>
> 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
> app.)
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."
>
> 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
> }
>
> }
>
> myclass::init();
>
> Slightly inelegant.
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)
self::loadBar();
return self::$bar;
}
}
Navigation:
[Reply to this message]
|