PHP中对象和类之间的区别? [英] Difference between object and class in PHP?

查看:128
本文介绍了PHP中对象和类之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP中的Object和Class有什么区别?

What is the difference between Object and Class in PHP? I ask because, I don't really see the point to both of them.

你能用好例子告诉我们的区别吗?

Can you tell me the difference with a good example?

推荐答案

我假设您有在基本PHP OOP上阅读手册

类用于 define 对象的属性,方法和行为。对象是类中创建的事物。将类视为一个蓝图,将一个对象作为实际的构建,按照蓝图(类)构建。

A class is what you use to define the properties, methods and behavior of objects. Objects are the things you create out of a class. Think of a class as a blueprint, and an object as the actual building you build by following the blueprint (class). (Yes, I know the blueprint/building analogy has been done to death.)

// 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 类。回到蓝图/建筑类比,认为它是使用相同的蓝图建造两个不同的建筑物。

The objects here are distinct (A and B), but they are both objects of the MyClass class. Going back to the blueprint/building analogy, think of it as using the same blueprint to build two different buildings.

这是另一个片段,实际上谈论建筑物,如果你需要一个更多字面示例:

Here's another snippet that actually talks about buildings if you need a more literal example:

// 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();

这篇关于PHP中对象和类之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆