问题描述
我有两个代码(与static关键字相关),我希望输出相同的结果,但实际上输出是不同的,为什么?
I have two codes(related to static keyword) which I expect output the same result, but actually the outputs are different, why?
code1输出:1
code1 output:1
<?php
class base {
public static $var = 1;
}
class sub extends base {
public static $var = 2;
}
echo base::$var;
?>
code2输出:2
code2 output: 2
<?php
class base2 {
public static $var2 = 1;
}
class sub2 extends base2 {
}
sub2::$var2 = 2;
echo base2::$var2;
?>
$ b
谢谢!
Thanks!
推荐答案
我想再添加一点。
STATIC变量不与任何特定实例/对象相关联的类。因此,您使用Parent Class引用或Child Class引用修改变量,相同的副本将被修改。
STATIC variable are not associated to any particular instance/object of a class. Hence you modify the variable with Parent Class reference or Child Class reference, the same copy gets modified.
因此,除了将Public Static理解为Global之外,请将其理解为不与任何特定实例相关联,因此通过任何类层次结构引用,您可以更新静态变量,相同的内存位置更新。
Hence apart from understanding Public Static as Global, Please understand it as not associated to any particular instance, hence with any class hierarchy reference you update a static variable , same memory location gets updated.
-
Vinod
这篇关于php静态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!