Difference between object and class in PHP?

2019-02-02 05:29发布

问题:

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?

回答1:

I assume you have read the manual on basic PHP OOP.

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

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


回答2:

For the new developers:

Class

A class is a collection of method and variables

class Test{

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

  }
}

Object

Object is a instance of a class (when you want to use your class and the thing you create)

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