php類對象中__get()和__set()方法使用教程

來源:互聯網
上載者:User
問1:

class Test{

private $aa=1;

function __get($proName){return $this->proName;}

}

class subTest extends Test{

private $aa=2;

}

$test=new subTest();

echo $test->aa;

求解釋,為啥輸出1?

答:當試圖從類的外部存取私人屬性時,__get方法會被調用,如果它存在的話subTest繼承了Test類,並試圖重載aa,但是沒有__get()方法,當執行個體化subTest類後訪問它的私人屬性,由於__get()方法,所以預設將調用父類的__get方法,當然訪問的也是父類的aa屬性,如果要輸出2可以為subTest類添加__get()

追問:那繼承父類的方法能不能訪問子類的成員屬性

class Test{

protected $aa=1; function __get($proName){return $this->$proName;}

}

class subTest extends Test{

protected $aa=2;

}

$test=new subTest();

echo $test->aa;

答:這裡輸出2,因為子類覆蓋了從父類繼承來的屬性aa,因為他們都是protected的,所以可以覆蓋

追問:

class Test{

private $aa=1;

function __get($proName){

return $this->$proName;

}

class subTest extends Test{

protected $aa=2;

}

$test=new subTest();

echo $test->aa;

答:這次輸出1,是因為子類並沒有覆蓋父類的屬性而且沒有自己的__get方法,當訪問同一個屬性時,php預設將其識別為private,也就是以父類的訪問限定符為標準,識別private後就會調用__get()方法,所以輸出1

對應的__set()是設定屬性的值,原理相似。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.