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:
| Aspect | Class | Object |
|---|---|---|
| Definition | A template or blueprint that defines properties (variables) and methods (functions). | An instance of a class created in memory. |
| Existence | Exists in code (definition only). | Exists at runtime (after you use new). |
| Purpose | Describes how objects of that type will look and behave. | Represents actual data and behavior in memory. |
| Memory Usage | Does not take memory for properties until an object is created. | Occupies memory for storing property values. |
| Creation | Defined using the class keyword. | Created using the new keyword. |
| Example in Real Life | Blueprint 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
🔹 Class → Car (blueprint)
🔹 Object → $myCar (real car with color and model).
Example: Mobile Phone
| Term | Real-World Example |
|---|---|
| Class | The 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. |
