在PHP中,Object和Class有什么区别?我之所以问是因为我不太明白它们的存在意义。
你能给我用一个好的例子来说明它们的差异吗?
假设你已经阅读了有关PHP基本面向对象编程的手册。
类是用来定义对象属性、方法和行为的,而对象则是从类中创建出来的东西。可以将类看作一个蓝图,将对象看作按照蓝图(类)建造出来的实际建筑物。(是的,我知道蓝图/建筑物的比喻已经用烂了。)
// 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();
private $number_of_floors = 5;
和private $color;
被称为“对象变量/属性”?而public function __construct($paint)
则被称为“类构造函数”。那么,为什么不像“类构造函数”一样,将它们称为“类变量/属性”,而不是“对象变量/属性”呢? - codenext针对新开发者:
类
类是一组方法和变量的集合。
class Test{
const t = "OK";
var $Test;
function TestFunction(){
}
}
对象
对象是类的一个实例(当您想要使用您创建的类和其它实例时)。
$test = new Test();
$test->TestFunction();//so here you can call to your class' function through the instance(Object)
类是包含结构和行为定义的一组,而对象则是具有结构和行为的任何东西。对象是类的实例,我们可以创建多个相同类的对象。