PHP5.0物件模型的屬性和方法分析_PHP教程

來源:互聯網
上載者:User
今天我們向大家介紹的是關於可以聯用->,如果一個對象的屬性包含了一個對象,你可以使用兩個->運算子來得到內部對象的屬性。 你甚至可以用雙重引用的字串來放置這些運算式。 下面的例子中,對象House中的屬性room包含了一組Room對象。

存取方法和訪問屬性類似。->運算子用來指向執行個體的方法。 在下面的中調用getLastLogin就是。方法執行起來和類外的函數幾乎相同。

如果一個類從另一類中繼承而來,父類中的屬性和方法將在子類中都有效,即使在子類中沒有聲明。 像以前提到過的,繼承是非常強大的。 如果你想訪問一個繼承的屬性,你只需要像訪問基類自己的屬性那樣引用即可,使用::運算子。

 
  1. class Room
  2. {
  3.  public $name;
  4.  function __construct($name="unnamed")
  5.  {
  6. $this->name = $name;
  7.  }
  8. }
  9. class House
  10. {
  11.  //array(促銷產品 主營產品) of rooms
  12.  public $room;
  13. }
  14. //create empty house
  15. $home = new house;
  16. //add some rooms
  17. $home->room[] = new Room("bedroom");
  18. $home->room[] = new Room("kitchen");
  19. $home->room[] = new Room("bathroom");
  20. //show the first room of the house
  21. print($home->room[0]->name);
  22. ?>


PHP5.0物件模型有兩個特殊的命名空間:parent命名空間指向父類,self命名空間指向當前的類。下面的例子中顯示了如何用parent命名空間來調用父類中的建構函式。 同時也用self來在建構函式中調用另一個類方法。

 
  1. class Animal //動物
  2. {
  3.  public $blood; //熱血or冷血屬性
  4.  public $name;
  5.  public function __construct($blood, $name=NULL)
  6.  {
  7. $this->blood = $blood;
  8. if($name)
  9. {
  10.  $this->name = $name;
  11. }
  12.  }
  13. }
  14. class Mammal extends Animal //哺乳動物
  15. {
  16.  public $furColor; //皮毛顏色
  17.  public $legs;
  18.  function __construct($furColor, $legs, $name=NULL)
  19.  {
  20. parent::__construct("warm", $name);
  21. $this->furColor = $furColor;
  22. $this->legs = $legs;
  23.  }
  24. }
  25. class Dog extends Mammal
  26. {
  27.  function __construct($furColor, $name)
  28.  {
  29. parent::__construct($furColor, 4, $name);
  30. self::bark();
  31.  }
  32.  function bark()
  33.  {
  34. print("$this->name says 'woof!'");
  35.  }
  36. }
  37. $d = new Dog("Black and Tan", "Angus");
  38. ?>

對於對象的成員來是這樣調用的:如果你需要在運行時確定變數的名稱,你可以用$this->$Property這樣的運算式。 如果你想調用方法,可以用$obj->$method()。

你也可以用->運算子來返回一個函數的值,這在PHP以前的版本中是不允許的。例如,你可以寫一個像這樣的PHP5.0物件模型的運算式: $obj->getObject()->callMethod()。這樣避免了使用一個中間變數,也有助於實現某些設計模式,如Factory模式。


http://www.bkjia.com/PHPjc/446432.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/446432.htmlTechArticle今天我們向大家介紹的是關於 可以聯用->,如果一個對象的屬性包含了一個對象,你可以使用兩個->運算子來得到內部對象的屬性。 你甚...

  • 聯繫我們

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