OOP. static property in method scope?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

OOP. static property in method scope?

Post 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
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

remove self::
static $returnValue defines a static variable in the scope of the function/method, not of the class
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

Post 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 :(
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

http://www.php.net/manual/en
Chapter 12. Variables
Variable scope
Using static variables
;)
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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;
    }
}
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

Post 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.
Post Reply