php - PHP 中对象和类的区别?

标签 php oop class object

PHP中的对象和类有什么区别?我问是因为,我真的不明白他们俩的意义。

你能用一个好例子告诉我区别吗?

最佳答案

我假设你有 read the manual关于基本的 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();

这里的对象是不同的(A 和 B),但它们都是 MyClass 类的对象。回到蓝图/建筑类比,将其视为使用相同的蓝图 build 两座不同的建筑。

如果您需要更直白的示例,这里还有另一个实际谈论建筑物的片段:

// 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 - PHP 中对象和类的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4837492/

相关文章:

actionscript-3 - 此类如何与声音连接?

php - 有什么原因导致这个 cron 作业无法正常工作吗

c++ - C++多重继承和访问说明符:从基类及其派生继承

c++ - 我可以使用哪些设计模式?

c++ - 类型转换结构和类

c# - 我需要一个解决方案来消除类中的公共(public)字符串

php - Styles.php 有条件的 PHP/CSS 在 IE 9 中不工作

javascript - php 中的 url 参数名称是否区分大小写?如果不区分大小写,它们是否可以轻松标准化(并设为小写等)?

可靠地设置 Etag

javascript - 从异步调用访问另一个对象原型(prototype)上的对象