Difference between object and class in PHP?

后端 未结 3 1902
谎友^
谎友^ 2020-12-28 14:50

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 g

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-28 15:03

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

提交回复
热议问题