第六節 訪問屬性和方法 [6]_PHP教程

來源:互聯網
上載者:User
一個對象執行個體的屬性是變數,就像PHP的其他變數一樣. 但是你必須使用->運算子來引用它們. 不需要在屬性前使用美元符$. 例如, 6.1中列印User對象的name屬性那一行.

可以聯用->,如果一個對象的屬性包含了一個對象,你可以使用兩個->運算子來得到內部對象的屬性. 你甚至可以用雙重引用的字串來放置這些運算式. 看6.5中的例子,對象House中的屬性room包含了一組Room對象.

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

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

class Room
{
public $name;

function __construct($name="unnamed")
{
$this->name = $name;
}
}

class House
{
//array of rooms
public $room;
}

//create empty house
$home = new house;

//add some rooms
$home->room[] = new Room("bedroom");
$home->room[] = new Room("kitchen");
$home->room[] = new Room("bathroom");

//show the first room of the house
print($home->room[0]->name);
?> PHP有兩個特殊的命名空間:parent命名空間指向父類,self命名空間指向當前的類. 例子6.6中顯示了如何用parent命名空間來調用父類中的建構函式. 同時也用self來在建構函式中調用另一個類方法.

class Animal file://動物
{
public $blood; file://熱血or冷血屬性
public $name;
public function __construct($blood, $name=NULL)
{
$this->blood = $blood;
if($name)
{
$this->name = $name;
}
}
}

class Mammal extends Animal file://哺乳動物
{
public $furColor; file://皮毛顏色
public $legs;

function __construct($furColor, $legs, $name=NULL)
{
parent::__construct("warm", $name);
$this->furColor = $furColor;
$this->legs = $legs;
}
}

class Dog extends Mammal
{
function __construct($furColor, $name)
{
parent::__construct($furColor, 4, $name);

self::bark();
}

function bark()
{
print("$this->name says 'woof!'");
}
}

$d = new Dog("Black and Tan", "Angus");
?> 第四節中介紹了如何調用函數. 對於對象的成員來是這樣調用的:如果你需要在運行時確定變數的名稱,你可以用$this->$Property這樣的運算式. 如果你想調用方法,可以用$obj->$method().

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

http://www.bkjia.com/PHPjc/314117.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/314117.htmlTechArticle一個對象執行個體的屬性是變數,就像PHP的其他變數一樣. 但是你必須使用-運算子來引用它們. 不需要在屬性前使用美元符$. 例如, 6.1中列印User對...

  • 聯繫我們

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