php static property

后端 未结 4 655
隐瞒了意图╮
隐瞒了意图╮ 2021-01-08 01:11

I have two code snippets (regarding the static keyword) which I expect them to have same output, but actually the outputs are different.

The question is

4条回答
  •  耶瑟儿~
    2021-01-08 01:46

    If you pass a static variable to a subclass, then this variable is shared (it always has the same value in both classes). If you overwrite the static variable in a subclass, then its a new static variable independent of the static variable from the parent.

    In Snippet 1 base::var and sub::var have different memory allocations, because you defined $var = 2; in the class sub.

    In Snippet 2 base::var and sub::var have the same memory allocation, because you did not specify $var2 in the class sub2.

    Thats why base:var is not changing. It would also not change if you change $var from sub class later like this:

    class base
    {
        public static $var = 1;
    }
    
    class sub extends base
    {
        public static $var = 2;
    }
    sub::var = 3
    echo base::var; // Outputs 1
    

提交回复
热议问题