|
|
|
|
|
在面向?qū)ο缶幊讨?,類是一個結(jié)構(gòu),這個結(jié)構(gòu)定義屬性和方法的集合。它可以被看作是一個模板。例如:
class Item {
public $itemType; /* e.g. this could be "Book" or "CD" */
public $price;
public function printPrice() {
echo "The price of this {$this->itemType} is {$this->price} dollars.";
}
}
$catch22 = new Item();
$catch22->itemType = "Book";
$catch22->price = 25;
$catch22->printPrice(); /* outputs The price of this Book is 25 dollars. */
$americanPrayer = new Item();
$americanPrayer->itemType = "CD";
$americanPrayer->price = 22;
$americanPrayer->printPrice(); /* outputs The price of this CD is 22 dollars */
注意在這個例子中,$catch22 和 $americanPrayer 是兩個對象。對象是一個類的實例。他們共享類定義的公共結(jié)構(gòu)。公共結(jié)構(gòu)由屬性(上述例子中的 $itemType 和 $price)和方法(上述例子中的函數(shù) printPrice() )組成。然而,不同對象的熟悉可能不同。
在上述例子中,同一類的兩個對象的 price 和 itemType 是不同的,但是兩個對象都有一個 printPrice() 方法,一個 price 和一個 itemType 屬性被使用。
比較表
類 | 對象 | |
---|---|---|
定義 | 類是一個單個單元中綁定數(shù)據(jù)成員和相關(guān)方法的結(jié)構(gòu)。 | 類的實例或變量 |
存在 | 它是一個邏輯存在 | 它是一個物理存在 |
內(nèi)存分配 | 當它創(chuàng)建時,內(nèi)存空間未分配 | 當它創(chuàng)建時,要分配內(nèi)存空間 |
聲明/定義 | 定義創(chuàng)建一次 | 當你需要時可以創(chuàng)建很多次 |
理解類和對象之間的區(qū)別的另一種方法是把類作為模具,而對象是作為使用模具產(chǎn)生的物品。