php物件導向的簡單總結 $this $parent self

來源:互聯網
上載者:User

標籤:傳遞   str   stat   context   play   php   否則   class   error   

$this->方法() 的例子:

 

1 class baseClass{

2 public function testFunc(){

3 echo "\n" . ‘I`m boss‘;

4 }

5 }

6

7 class parentClass extends baseClass{

8 public function testFunc(){

9 echo "\n" . ‘I`m the up‘;

10 }

11 }

12

13 class testClass extends parentClass{

14 var $nick = ‘‘;

15

16 public function __construct($nick){

17 $this->nick = $nick;

18 }

19

20 public function display(){

21 echo $this->nick;

22 $this->testFunc();

23 }

24 }

25

26 $otestClass1 = new testClass(‘frank‘);

27 $otestClass1->display();

 

這樣的代碼最後的輸出結果是什麼呢?關鍵是看testFunc()方法。

如果在類中用$this調用一個當前類中不存在的方法或變數,它會依次去父類尋找,直到找不到再報錯

基於第一條,如果找到了需要的方法或變數,就會停止尋找,如果其上級父類中還有同樣的,則選擇當前找到的

所以上面代碼輸出為:

frank

I`m the up

 

3. 關於parent::

parent是對父類的引用

 

1 <?php

2 class A {

3 public $a = ‘aa‘;

4 public function callFunc(){

5 echo ‘parent‘;

6 }

7 }

8

9 class B extends A{

10 public function __construct(){

11 parent::callFunc();

12 echo "\n" . $this->a;

13 }

14 }

15

16 $oB = new B;

比如,上面的代碼中,在class B中,若要調用其父類A中的callFunc()方法,就需要使用parent::callFunc(),但A類中此方法必須是public修飾的,否則會提示 Fatal error: Call to private method A::callfunc() from context ‘B‘...

另外需要注意的是,對於父類中的屬性$a,調用的時候用$this,用parent就訪問不到了。若$a在A類中是這樣定義的:public static $a,則訪問的時候就需要parent::$a

注意,parent不具備傳遞性,它只能代表當前類的父類,若此例子A類繼承base類,在base類中定義baseFunc()方法,那麼在B類中使用parent::baseFunc()是錯誤的,只能在A類中這樣使用。

4. self::又指向哪裡?

簡單的說,self和某具體執行個體沒有關係,它只指向當前類,不會受某具體類對象的影響

 

1 class testClass{

2 public static $count = 0;

3 public $num = 0;

4

5 function __construct(){

6 self::$count++;

7 $this->num++;

8 }

9

10 function display(){

11 echo self::$count . "\n";

12 echo $this->num . "\n";

13 }

14 }

15

16 $oTest1 = new testClass;

17 $oTest1->display(); //輸出: 1 1

18

19 $oTest2 = new testClass;

20 $oTest2->display(); //輸出: 2 1

 

上面例子中self::$cout始終指向該類本身,而$num是單獨存在於各個具體執行個體中的。

php物件導向的簡單總結 $this $parent self

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.