self和satic

在 php 的面向对象编程中,总会遇到:

1
2
3
4
5
6
7
8
class test{
public static function test(){
self::func();
static::func();
}

public static function func(){}
}

可你知道 self 和 static 的区别么?

其实区别很简单,只需要写几个 demo 就能懂:

demo for self

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Car
{
public static function model(){
self::getModel(); // 注意:self
}

protected static function getModel(){
echo "This is a car model";
}
}
Car::model(); // This is a car model

Class Taxi extends Car
{
protected static function getModel(){
echo "This is a Taxi model";
}
}
Taxi::model(); // This is a car model

demo for static

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Car
{
public static function model(){
static::getModel(); // 注意:static
}

protected static function getModel(){
echo "This is a car model";
}
}
Car::model(); // This is a car model

Class Taxi extends Car
{
protected static function getModel(){
echo "This is a Taxi model";
}
}
Taxi::model(); // This is a Taxi model

总结

self 只能引用当前类中的方法,而 static 关键字允许函数能够在运行时动态绑定类中的方法,也叫延迟绑定