Classes and Objects are the two main aspects of object-oriented programming. A **Class** acts as a blueprint or a template, while an **Object** is an individual instance created from that blueprint.
A class is a user-defined data type. It defines the structure of the data and the functions that can operate on that data. Think of a class as a blueprint for a house. It shows where the walls, doors, and windows should be, but it isn't a house itself.
You define a class using the class keyword followed by the name of the class.
<?php
class Fruit {
// Properties and methods go here
}
?>
UserAccount, ProductManager).
Inside a class, you define variables (called **Properties**) and functions (called **Methods**).
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
?>
$this keyword refers to the **current instance** of the class. It is used to access properties or methods within the class definition.
An object is an instance of a class. If the class is the blueprint, the object is the actual house built from that blueprint. You can create many objects from a single class, and each object can have its own data.
You create an object using the new keyword.
<?php
// Instantiate the object
$apple = new Fruit();
$banana = new Fruit();
// Access properties and methods using ->
$apple->set_name('Apple');
$banana->set_name('Banana');
echo $apple->get_name(); // Outputs: Apple
echo $banana->get_name(); // Outputs: Banana
?>
| Feature | Class | Object |
|---|---|---|
| Analogy | A Blueprint / Template. | A Physical Building / Instance. |
| Memory | Does not occupy memory space. | Occupies memory space when created. |
| Existence | Defined once in your code. | Multiple instances can exist at once. |
You can check if an object belongs to a specific class using the instanceof keyword. This is very useful for validation.
<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit); // Outputs: bool(true)
?>
class keyword to define a class.new keyword to create an object.-> (arrow operator) to access properties and methods of an object.