Reputation: 11
Why there are static variables inside dynamic methods in PHP? I supposed to use static to store value between method calls, but discovered that static vars are just like static fields (members) of class.
class A {
public function B() {
static $C;
if (!isset($C) {
$C = rand();
}
echo $C."\n";
}
}
$i1 = new A;
$i1->B();
$i2 = new A;
$i2->B();
What is the best way to store value (cache it) between method's call?
Upvotes: 1
Views: 557
Reputation: 57709
A static
variable is similar to a static member. One minor difference is that it's scoped to the function you've declared it in.
Keep in mind that static members have one other property: they are shared over all instances of a class. Sample code:
class A {
function foo () {
static $a = 0;
$a += 1;
var_dump($a);
}
function bar() {
self::$a; // Fatal error: Access to undeclared static property: A::$a
}
}
$a = new A();
$a->foo(); // 1
$a->foo(); // 2
$a2 = new A();
$a2->foo(); // 3!
This is problematic. My recommendation is: don't use static variables. Just have a private non-static member:
class A {
private $a = 0;
function foo () {
$this->a += 1;
var_dump($this->a);
}
}
$a = new A();
$a->foo(); // 1
$a->foo(); // 2
$a2 = new A();
$a2->foo(); // 1
If you need to cache a value make that it's own entity:
$cache = new ValueProvider();
$a = new A($cache);
$a2 = new A($cache);
Now A
doesn't need to know how ValueProvider
get's the value, or even that it's cached. $a
and $a2
share their ValueProvider
, but they don't know about that, and that's good.
Upvotes: 3
Reputation: 15760
In the code you've given, the variable $C
maintains it's value between successive calls to function B()
. It is also private to the function B(). Note, however, that it is truly static
- every instance of A
will have the same value of $C
in it's method B
.
The best way to store the value? That depends on what you're using it for:
B
and you don't mind having the same value of $C
for every instance of A
, then this is the way to go.A
, then make it a (private) member variable (although in this case, it will be accessible from every method of A
).Upvotes: 0