技術(shù)頻道導航
HTML/CSS
.NET技術(shù)
IIS技術(shù)
PHP技術(shù)
Js/JQuery
Photoshop
Fireworks
服務(wù)器技術(shù)
操作系統(tǒng)
網(wǎng)站運營

贊助商

分類目錄

贊助商

最新文章

搜索

實例說明類與對象的關(guān)系及區(qū)別

作者:admin    時間:2016-8-3 17:42:42    瀏覽:

在面向?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)生的物品。

標簽:   對象  
相關(guān)文章
    x