对象成员函数中的PHP和静态变量 [英] PHP and Static Variables in Object Member Functions
问题描述
直到今天,我还认为我对static修饰符的工作原理掌握得相当好.我知道(用外行人的话)函数中的静态变量不会在对该函数的调用之间重置",并且我知道可以通过类本身(而不是实例化)对其进行调用来访问类中的静态变量和函数.班级).
Up until today, I thought I had a fairly good grasp of how the static modifier worked. I know that (in laymans terms) a static variable in a function does not 'reset' across calls to that function, and I know that static variables and functions on a class are accessible by calling upon them through the class itself (not an instantiation of the class).
我的问题是这样的:今天我发现,如果我在类上声明了 non-static 函数的静态变量 inside ,则该类的所有实例共享分别调用成员函数的静态变量.
My problem is this: today I found that if I declare a static variable inside of a non-static function on a class, all instantiations of that class share that static variable in separate calls to the member function.
例如:
class A {
public function GetValue() {
static $value = 0;
$value++;
return $value;
}
}
$instance_1 = new A();
$instance_2 = new A();
echo $instance_1->GetValue();
echo $instance_1->GetValue();
echo $instance_2->GetValue();
echo $instance_2->GetValue();
echo $instance_1->GetValue();
echo $instance_1->GetValue();
请注意,GetValue函数既未声明为静态,也未以静态方式使用(例如,在类本身上调用).
Notice that the GetValue function is neither declared as static or used in a static way (as in, called on the class itself).
现在,我一直以为它将输出:121234
Now, I always assumed that this would output: 121234
相反,我发现它将输出:123456
Instead, I find that it will output: 123456
就像我说的,如果静态变量$ value在静态函数内部,我会理解这一点.但是,由于它位于一个非静态函数中,我只是假设它只会绑定"到每个单独实例内的函数中.
Like I say, I would understand this if the static variable $value was inside of a static function. However, with it being inside a non-static function I just assumed that it would only be 'tied' to the function 'within' each individual instantiation.
我想我的问题是双重的,那么... 1)这是错误还是预期的行为? 2)其他语言是否以相同的方式处理这些静态内部非静态"变量,或者这是PHP所独有的?
I guess my question is twofold, then... 1) is this a bug or expected behaviour? 2) do other languages treat these 'static inside non-static' variables the same way, or is this unique to PHP?
推荐答案
- 这是预期的.
- 在C ++中(也可能在其他情况下)也是如此.
您应该认为非静态类成员函数就像普通函数一样,但是具有隐式的$this
参数,该参数由解释器自动提供. (这正是大多数语言中实现它们的方式.)
You should think of non-static class member functions as if they were just like ordinary functions, but with an implicit $this
argument that is automatically provided by the interpreter. (That's exactly how they're implemented in most languages.)
这篇关于对象成员函数中的PHP和静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!