this,static和self。
self和this还是很好区分的,可是self和static就很糊涂了,两者都能调用静态的方法和属性,看似使用上没有什么太大的分别,但是实际上分别很大,先来看下面这一段代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 1 class Boo {
2
3 protected static $str = "This is class Boo";
4
5 public static function get_info(){
6
7 echo get_called_class()."<br>";
8 echo self::$str;
9 }
10 }
11 class Foo extends Boo{
12
13 protected static $str = "This is class Foo";
14
15 }
16
17 Foo::get_info();
18
19
输出结果:
下面我们稍作修改代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 1 class Boo {
2
3 protected static $str = "This is class Boo";
4
5 public static function get_info(){
6
7 echo get_called_class()."<br>";
8 echo static::$str;
9// echo self::$str;
10 }
11 }
12 class Foo extends Boo{
13
14 protected static $str = "This is class Foo";
15
16 }
17
18 Foo::get_info();
19
20
输出结果:
我们惊奇的发现结果不是我们预期的那样,为什么呢?
php官方也说过,大概意思是说self调用的就是本身代码片段这个类,而static调用的是
从堆内存中提取出来,访问的是当前实例化的那个类,那么 static 代表的就是那个类,例子比较容易明白些。
准确说,这是后期静态绑定的功能。后期静态绑定工作原理是存储了在上一个“非转发调用”(non-forwarding call)的类名。当进行静态方法调用时,该类名即为明确指定的那个(通常在 :: 运算符左侧部分);