Hello World


  • 首页

  • 归档

静态绑定self和static的区别

发表于 2019-05-07

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指向使用类。

Hexo

发表于 2019-04-23

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1
$ hexo new "My New Post"

More info: Writing

Run server

1
$ hexo server

More info: Server

Generate static files

1
$ hexo generate

More info: Generating

Deploy to remote sites

1
$ hexo deploy

More info: Deployment

lvminmin

2 日志
© 2019 lvminmin
由 Hexo 强力驱动
|
主题 — NexT.Muse v5.1.4