【问题标题】:Difference between object and class in PHP?PHP中对象和类的区别?
【发布时间】:2011-01-29 14:52:45
【问题描述】:

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

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

【问题讨论】:

  • 类在 PHP 中是必需的,因为它遵循较旧且更静态的 OOP 范例。在prototype-based languages (JavaScript, Lua) 中,您实际上只需要对象。因此,对课程需求的困惑并非没有道理。

标签: php oop class object


【解决方案1】:

我假设您在基本的 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 类的对象。回到蓝图/建筑的类比,把它想象成使用相同的蓝图来建造两座不同的建筑。

如果您需要一个更字面的例子,这里还有一个实际谈论建筑物的 sn-p:

// 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 将对象视为引用或句柄,这意味着每个变量都包含一个对象引用而不是整个对象的副本 +1
  • +1 非常好的教学示例!初学者经常混淆类和实例(对象)。
  • 我有一个问题,为什么private $number_of_floors = 5;private $color; 被称为Object variables/propertiespublic function __construct($paint) 称为 Class constructor。那么,为什么不与Class constructor 相同,它们被称为Class variable/properties 而不是Object variables/properties
  • @codenext:你说得很好。其他语言(如 C#)调用实例构造函数,嗯,实例构造函数,尽管它们这样做主要是因为它们同时具有实例构造函数和静态构造函数。 PHP 没有静态构造函数,但我可以看到“类构造函数”可能会让来自 C# 或其他语言的人感到困惑。
  • 那么两个对象在内存方面的方法比另一个对象多?
【解决方案2】:

对于新开发者:

类是方法和变量的集合

class Test{

  const t = "OK";
  var $Test;
  function TestFunction(){

  }
}

对象

Object 是一个类的实例(当你想使用你的类和你创建的东西时)

$test = new Test();
$test->TestFunction();//so here you can call to your class' function through the instance(Object)

【讨论】:

  • 简单又好看! :)
【解决方案3】:

类是包含结构和行为的组定义,对象是任何具有结构和行为的东西。对象是一个类的实例,我们可以创建同一个类的多个对象。

【讨论】:

    猜你喜欢
    • 2011-03-02
    • 2017-01-20
    • 2017-10-30
    • 2011-03-27
    • 2017-12-13
    • 2010-12-17
    • 2015-05-08
    • 2020-02-06
    • 1970-01-01
    相关资源
    最近更新 更多