2011-01-29 35 views
22

PHP中的Object和Class有什麼區別?我問,因爲我並沒有真正意識到這兩點。PHP中的對象和類的區別?

你能告訴我與好例子的區別

+1

類是必要的,PHP,因爲它遵循舊的和更多的靜態OOP範例。在[基於原型的語言(JavaScript,Lua)](http://en.wikipedia.org/wiki/Prototype-based_programming)中,你實際上只需要對象。所以關於課堂需要的混淆並非沒有理由。 – mario 2011-01-29 15:40:49

回答

46

我假設你在基本PHP OOP上有read the manual

一個類是你用來對定義對象的屬性,方法和行爲。對象是你在課堂上創建的東西。按照藍圖(課程),您可以將課程視爲藍圖,並將對象視爲實際建築物(是的,我知道的藍圖/建築比喻已經做了死亡。)

// Class 
class MyClass { 
    public $var; 

    // Constructor 
    public function __construct($var) { 
     echo 'Created an object of MyClass'; 
     $this->var = $var; 
    } 

    public function show_var() { 
     echo $this->var; 
    } 
} 

// Make an object 
$objA = new MyClass('A'); 

// Call an object method to show the object's property 
$objA->show_var(); 

// Make another object and do the same 
$objB = new MyClass('B'); 
$objB->show_var(); 

這裏的對象是不同的(A和B),但他們是MyClass類的兩個對象。回到藍圖/建築的比喻,把它看成是用同樣的藍圖來建造兩座不同的建築。

這裏的,如果你需要一個更字面的例子,實際上談論樓宇另一個片段:

// Class 
class Building { 
    // Object variables/properties 
    private $number_of_floors = 5; // Each building has 5 floors 
    private $color; 

    // Constructor 
    public function __construct($paint) { 
     $this->color = $paint; 
    } 

    public function describe() { 
     printf('This building has %d floors. It is %s in color.', 
      $this->number_of_floors, 
      $this->color 
     ); 
    } 
} 

// Build a building and paint it red 
$bldgA = new Building('red'); 

// Build another building and paint it blue 
$bldgB = new Building('blue'); 

// Tell us how many floors these buildings have, and their painted color 
$bldgA->describe(); 
$bldgB->describe(); 
+4

PHP以與引用或句柄相同的方式處理對象,這意味着每個變量都包含對象引用而不是整個對象的副本+1 – kjy112 2011-01-29 14:56:06

相關問題