PHP Classes and Objects Explained with Simple Examples
Objects are a key part of Object-Oriented Programming (OOP) in PHP. They allow you to group related data (properties) and functions (methods) together.
Think of an object like a real-world object—like a car.
- Properties (data): color, brand, speed
- Methods (actions): start(), stop(), accelerate()
In PHP, objects are created from classes.
What is a Class?
A class in PHP is a blueprint for creating objects. It defines properties (data) and methods (functions) that describe the object's characteristics and behavior. Classes promote code reusability, organization, and modularity in programs. Objects created from a class can access and use its properties and methods.
Example:
<?php
class Car
{
public $color; // Property
public $brand; // Property
// Method (function inside a class)
public function drive()
{
return "Driving the $this->color $this->brand car
How to Create an Object ?
An object is an instance of a class. When you create an object, you bring the class blueprint to life. Objects let you use the properties and methods defined in the class.Use the new keyword to create an object from a class.
Steps to Create an Object:
-
Use the
newkeyword:- The
newkeyword creates an object from a class.
- The
-
Access properties and methods with
->operator:- Use
->to set or get property values. - Use
->to call methods.
- Use
Example:
<?php
class Car
{
public $color; // Property
public $brand; // Property
// Method to display details
public function drive()
{
return "Driving the $this->color $this->brand";
}
}
// Create an object from Car class
$myCar = new Car(); // Object created
$myCar->color = "Red"; // Set property
$myCar->brand = "Toyota"; // Set property
echo $myCar->drive(); // Call method
// Output: Driving the Red Toyota
?>
Explanation:
$myCar = new Car();→ Creates a new object named$myCar.$myCar->color = "Red";→ Sets thecolorproperty to "Red".$myCar->drive();→ Calls thedrivemethod, using$thisto access object properties.