静态绑定self和static的区别

self示例

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Father
{
public function __construct()
{
$this->init();

self::test();
}

public function init()
{
echo 'father init...<br>';
}

public static function test()
{
echo "father test....<br>";
}
}
class Son extends Father
{
public function init()
{
echo 'son init..<br>';
}

public static function test()
{
echo "son test..<br>";
}
}

$son_obj = new Son();

运行结果

1
2
son init..
father test....

从运行结果看,调用init非静态方法,父类的方法已经被子类覆盖了;但使用self调用test静态方法,使用的还是父类的静态方法。

static示例

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Father
{
public function __construct()
{
$this->init();

static::test();
}

public function init()
{
echo 'father init...<br>';
}

public static function test()
{
echo "father test....<br>";
}
}
class Son extends Father
{
public function init()
{
echo 'son init..<br>';
}

public static function test()
{
echo "son test..<br>";
}
}

$son_obj = new Son();

运行结果

1
2
son init..
son test..

使用static调用静态方法使用了当前分类的静态方法

小结

简单通俗的来说,self就是写在哪个类里面,实际调用的就是这个类;static代表使用的这个类, 就是你在父类里写的static,然后被子类覆盖,使用的就是子类的方法或属性。

Ps:self指向本类,是类内指针;static指向使用类。