1
class A{

  static $var = true;

  function f(){

  }

}

vs

class A{

  function f(){
    static $var = true;

  }
}

There doesn't seem to be any difference. Are there any advantages of using one over the other?

Note that $var would be used in the f() function only. I understand that declaring it in the class header is required if the variable needs to be used in multiple functions

2 Answers 2

3

If you only use the static variable in the f function, there's only a scope difference, that means no difference as long as you don't try to use it elsewhere.

When used in local scope, the static variable value is kept between each function call. See Static variables part of this page.

Thanks insertusernamehere for pointing that out.

Sign up to request clarification or add additional context in comments.

2 Comments

I also would presume that static $var in a function is a logic error even if it's allowed by the PHP engine
That's not entirely true. A static variable in a function caches its value for the next call: "Another important feature of variable scoping is the static variable. A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.", from the PHP manual: "Using static variables".
1

In the later example you may only use the var inside the f function. The other is accessible anywhere from inside the class A::var or outside A::var

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.