HomePHP OOPSDifference between class and object in PHP

Difference between class and object in PHP

class and object

In PHP, class and object are related but not the same thing — one is the blueprint, and the other is the actual thing built from that blueprint.

An instance simply means a specific copy of something created from its blueprint (class).

Here’s the breakdown:

AspectClassObject
DefinitionA template or blueprint that defines properties (variables) and methods (functions).An instance of a class created in memory.
ExistenceExists in code (definition only).Exists at runtime (after you use new).
PurposeDescribes how objects of that type will look and behave.Represents actual data and behavior in memory.
Memory UsageDoes not take memory for properties until an object is created.Occupies memory for storing property values.
CreationDefined using the class keyword.Created using the new keyword.
Example in Real LifeBlueprint of a car.A specific car built from that blueprint.

Example in PHP:

<?php
// Class definition (blueprint)
class Car {
    public $color;
    public $model;

    public function startEngine() {
        return "Engine started";
    }
}

// Object creation (instance of class)
$myCar = new Car(); // Object
$myCar->color = "Red";
$myCar->model = "Toyota";

echo $myCar->color;       // Output: Red
echo $myCar->startEngine(); // Output: Engine started

🔹 ClassCar (blueprint)
🔹 Object$myCar (real car with color and model).

Example: Mobile Phone

TermReal-World Example
ClassThe design blueprint of a mobile phone (specs, dimensions, features). It says: “A phone will have a screen, battery, camera, and can make calls.”
Object (Instance)Your actual mobile phone in your hand — e.g., a black iPhone 14 with 256GB storage.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *