2011-01-29 68 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

相关问题