對于大多數 PHPer 來說,self 與 static 兩個 PHP 關鍵詞都不算陌生。我們學會通過self::xxxx
這種方式來調用當前類的靜態屬性和方法。而 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
|
// self 用法 1 :調用靜態成員屬性 class Person { protected static $maxAddressCount = 5; // 收獲地址創建最大數量。 public function test() { echo self:: $maxAddressCount ; } } $person = new Person(); $person ->test(); |
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
34
35
36
|
// self 用法 2 :調用靜態方法 class Person { protected static $maxAddressCount = 5; // 收獲地址創建最大數量。 protected static function getMaxAddressCount() { return self:: $maxAddressCount ; } public function test() { echo self::getMaxAddressCount(); } } $person = new Person(); $person ->test(); |
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
// self 用法 3 :創建一個當前對象 // 單例示例 class Person { private static $instance = null; private function __construct() {} final public static function getInstance() { if (self:: $instance == null) { self:: $instance = new self; } return self:: $instance ; } public function test() { echo "hello world!" ; } } $person = Person::getInstance(); $person ->test(); |
關于 static 關鍵詞的常見用法也在上面 3 個示例中得到綜合體現
我深信上面的用法,任何一個入門的 PHPer 都是非常熟悉的。現在我要講的是以下兩種方式:
new self()
與 new static()
的區別?
我相信很多人都知道new self()
創建一個當前類的對象,并不知道new static()
也能創建一個當前類的對象。
關于new static()
這種用法呢,在官方文檔有說明。地址:https://www.php.net/manual/zh/language.oop5.late-static-bindings.php
PHP 官方把這種方式稱為:后期靜態綁定。
官方示例 1:
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
|
class A { public static function who() { echo __CLASS__ ; } public static function test() { self::who(); } } class B extends A { public static function who() { echo __CLASS__ ; } } B::test(); |
因為 Class B 繼承了 Class A。 A 與 B 都有一個靜態方法who()
。此時通過B::test()
的時候,調用的實際上是 Class A 的who()
方法。
因為子類 Class B 的靜態方法who()
屬于在 Class A 之后的子類里面才定義的。而 PHP 的默認特性只允許調用最先定義的。
就這引出了后期靜態綁定的概念。
官方示例 2:
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
|
class A { public static function who() { echo __CLASS__ ; } public static function test() { static ::who(); // 后期靜態綁定從這里開始 } } class B extends A { public static function who() { echo __CLASS__ ; } } B::test(); |
我們把 Class A 里面的test()
方法體的self
更改為static
之后,static 代表的永遠是指向調用類。也就是說雖然在 Class A 父類里面定義的方法與子類有同名沖突的情況。但是,當子類調用的時候,那么自動切換到子類的靜態同名方法。取決于調用者。
大家可以通過運行以上兩個示例進行理解。
之所以會有本篇小節內容。是因為我在實際運行當中要繼承單例方法導致了這個問題。所以,才牽扯出這個特性。
到此這篇關于PHP Class self 與 static 異同與使用詳解的文章就介紹到這了,更多相關PHP Class self 與 static 內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.php.cn/php-weizijiaocheng-481717.html