简体   繁体   English

PHP静态类变量在初始实例化后仍保留值

[英]PHP static class variables still holding values after initial instantiation

I have: 我有:

class A {
    static $instances = 0;
    public $instance;

    public function __construct() {
        $this->instance = ++self::$instances;
    }
}

$a = new A();
$b = new A();

echo "<pre>";
print_r($a);
print_r($b);
echo "</pre>";

Outputs: 输出:

A Object
(
    [instance] => 1
)
A Object
(
    [instance] => 2
)

I know that static variables still retain their values after exiting functions but this is in a class context. 我知道静态变量在退出函数后仍会保留其值,但这是在类上下文中。 How come in this class context the class still retains the variable when a new instance is created. 在创建新实例时,该类在类上下文中的作用如何仍保留变量。

Any references to official documentation would be helpful. 任何对官方文档的引用都会有所帮助。

Static variables are not associated to any particular instance/object of a class. 静态变量不与类的任何特定实例/对象相关联。 The same is for the static variable inside of the class's method ... (comments in http://php.net/manual/en/language.oop5.static.php ) 类的方法内部的static变量也是如此...( http://php.net/manual/zh/language.oop5.static.php中的注释)

So if you declare a variable as static inside a function, it's static for the whole class and all of its instances, not for each object. 因此,如果您在函数内部将变量声明为静态变量,则对于整个类及其所有实例(而不是每个对象)而言,变量都是静态的。

and

The difference between static and non static members is only that a non static member is tied to an instance of a class although a static member is tied to the class, and not to a particular instance. 静态成员和非静态成员之间的区别仅在于,尽管静态成员与类(而不是特定实例)相关联,但非静态成员与类的实例相关联。 That is, a static member is shared by all instances of a class although a non static member exists for each instance of class. 也就是说,尽管类的每个实例都存在一个非静态成员,但该类的所有实例都共享一个静态成员。

I had to read this from the Java documentation to understand why: 我必须从Java文档中阅读以下内容以了解原因:

When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables. 当从同一类蓝图创建多个对象时,每个对象都有各自不同的实例变量副本。

Sometimes, you want to have variables that are common to all objects. 有时,您希望拥有所有对象共有的变量。 This is accomplished with the static modifier. 这可以通过static修饰符完成。 Fields that have the static modifier in their declaration are called static fields or class variables. 在声明中具有static修饰符的字段称为静态字段或类变量。 They are associated with the class, rather than with any object. 它们与类关联,而不与任何对象关联。 Every instance of the class shares a class variable, which is in one fixed location in memory. 该类的每个实例共享一个类变量,该变量位于内存中的一个固定位置。 Any object can change the value of a class variable... 任何对象都可以更改类变量的值...

新的实例化不会保留静态变量,而是您要增加类的$ instances,然后将结果保存到实例化的$ instance中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM