PHP中对象和类的区别?

bey*_*ski 25 php oop class object

PHP中的Object和Class有什么区别?我问,因为,我并没有真正看到他们两个人的意思.

你能告诉我一个很好的例子吗?

Bol*_*ock 51

我假设您已阅读有关基本PHP OOP 的手册.

类是用于定义对象的属性,方法和行为的类.对象是从类中创建的内容.将类视为蓝图,将对象视为您通过遵循蓝图(类)构建的实际构建.(是的,我知道蓝图/建筑类比已经完成了死亡.)

// 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();
Run Code Online (Sandbox Code Playgroud)

这里的对象是不同的(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();
Run Code Online (Sandbox Code Playgroud)

  • PHP以与引用或句柄相同的方式处理对象,这意味着每个变量包含一个对象引用而不是整个对象的副本+1 (4认同)
  • +1非常好和教育的例子!初学者经常会混淆类和实例(对象). (4认同)