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
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