Page 1 of 1

OOP. static property in method scope?

Posted: Fri Nov 03, 2006 3:24 am
by jmut
Hi...I think that was possible to do but not sure.

What I want is to decrease the load on a method.
Mehtod is used to create an array or whatever after heavy computation.

I want to do something like.

Code: Select all

class myclass
{

    public function methodname()
    {
        static $returnValue = '';

        if (!empty(self::$returnValue)) {
            return self::$returnValue;
        }
       //heavy computation here assigning self::$returnValue

        return self::$returnValue;
    }
}


$n = new myclass();
echo $n->methodname();
I get undeclared static property....of course I could move this static $returnValue = ''; to the class declaration and it will work...but really need this only for this one method. is it possible?
Thanks

Posted: Fri Nov 03, 2006 3:29 am
by volka
remove self::
static $returnValue defines a static variable in the scope of the function/method, not of the class

Posted: Fri Nov 03, 2006 5:20 am
by jmut
volka wrote:remove self::
static $returnValue defines a static variable in the scope of the function/method, not of the class
nice, thanks a lot
kind of not able to find this feature in the manual :(

Posted: Fri Nov 03, 2006 5:24 am
by volka
http://www.php.net/manual/en
Chapter 12. Variables
Variable scope
Using static variables
;)

Posted: Fri Nov 03, 2006 6:38 am
by Chris Corbyn
You only use self:: if the static is within class scope. You declared it in function scope so you just omit it.

You were sort of trying this:

Code: Select all

class myclass
{

    public static $returnValue = null;
    
    public function methodname()
    {
        if (self::$returnValue !== null) {
            return self::$returnValue;
        }
       //heavy computation here assigning self::$returnValue

        return self::$returnValue;
    }
}

Posted: Fri Nov 03, 2006 6:50 am
by jmut
yep, figured this out.
was thinking what might be the drawbacks of this usage though.
maybe more memmory usage or something...no idea yet...but prefer it compare to additional property in the class.