self和static的差异

其实很简单。

在没有继承的情况下是一样的。主要的差异体现在继承的情况下。

差异:

self:永远绑定代码所在类。当前定义类
static:调用时确定哪个类。当前调用类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Books
{
public static $title = 'Books';
public static function getTitleSelf()
{
return self::$title;
}
public static function getTitleStatic()
{
return static::$title;
}
}
class SmallBook extends Books
{
public static $title = 'small';
}

echo SmallBook::getTitleSelf().'<br />';
echo SmallBook::getTitleStatic().'<br />';
echo Books::getTitleStatic().'';
echo Books::getTitleSelf().'';

运行结果:

1
2
3
4
Books
small
Books
Books
一分支持,也是鼓励!
0%