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

贊助商

分類目錄

贊助商

最新文章

搜索

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

作者:admin    時(shí)間:2016-8-3 17:42:42    瀏覽:

在面向?qū)ο缶幊讨?,類是一個(gè)結(jié)構(gòu),這個(gè)結(jié)構(gòu)定義屬性和方法的集合。它可以被看作是一個(gè)模板。例如:

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 */

注意在這個(gè)例子中,$catch22$americanPrayer 是兩個(gè)對(duì)象。對(duì)象是一個(gè)類的實(shí)例。他們共享類定義的公共結(jié)構(gòu)。公共結(jié)構(gòu)由屬性(上述例子中的 $itemType 和 $price)和方法(上述例子中的函數(shù) printPrice() )組成。然而,不同對(duì)象的熟悉可能不同。

在上述例子中,同一類的兩個(gè)對(duì)象的 price 和 itemType 是不同的,但是兩個(gè)對(duì)象都有一個(gè) printPrice() 方法,一個(gè)  price 和一個(gè) itemType 屬性被使用。

比較表

  對(duì)象
定義 類是一個(gè)單個(gè)單元中綁定數(shù)據(jù)成員和相關(guān)方法的結(jié)構(gòu)。 類的實(shí)例或變量
存在 它是一個(gè)邏輯存在 它是一個(gè)物理存在
內(nèi)存分配 當(dāng)它創(chuàng)建時(shí),內(nèi)存空間未分配 當(dāng)它創(chuàng)建時(shí),要分配內(nèi)存空間
聲明/定義 定義創(chuàng)建一次 當(dāng)你需要時(shí)可以創(chuàng)建很多次

理解類和對(duì)象之間的區(qū)別的另一種方法是把類作為模具,而對(duì)象是作為使用模具產(chǎn)生的物品。

標(biāo)簽:   對(duì)象  
相關(guān)文章
    x
    • 站長推薦
    /* 左側(cè)顯示文章內(nèi)容目錄 */