Object-oriented programming in PHP helps you organize code into small, reusable units. Instead of writing all logic as separate functions, you group related data and behavior inside classes.
PHP supports important OOP concepts like classes, objects, encapsulation, inheritance, abstraction, interfaces, traits, and polymorphism. These concepts are useful when your PHP project grows beyond a few simple scripts.
In this tutorial, we will learn the main PHP OOP concepts with simple examples. Then we will build a small product cart demo to see how these concepts work together in a real PHP program.
Quick Answer: What are OOP concepts in PHP?
OOP concepts in PHP are programming features that help you write structured, reusable, and maintainable code using classes and objects. The main concepts are class, object, encapsulation, inheritance, abstraction, polymorphism, interface, and trait.
In short:
- Class is a blueprint.
- Object is an instance of a class.
- Encapsulation protects data inside a class.
- Inheritance lets one class reuse another class.
- Abstraction hides internal details and exposes only what is needed.
- Polymorphism allows different classes to respond to the same method call in different ways.
Why use OOP in PHP?
OOP is useful when a PHP application has related data and actions. For example, a product has a name, price, and discount logic. A user has a name, email, and login behavior.
When this logic is kept inside classes, the code becomes easier to read and change. This is one reason modern PHP frameworks like Laravel and Symfony are built around object-oriented programming.
OOP helps in these ways:
- It keeps related code together.
- It avoids repeated code.
- It makes large codebases easier to maintain.
- It allows one class to reuse or extend another class.
- It makes testing and debugging easier.
PHP Class and Object Example
A class is a blueprint. An object is a real instance created from that blueprint.
In the example below, the Product class defines properties and methods related to a product. Then we create an object from that class.
<?php
class Product
{
public $name;
public $price;
public function setProduct($name, $price)
{
$this->name = $name;
$this->price = $price;
}
public function displayProduct()
{
return $this->name . " costs $" . $this->price;
}
}
$product = new Product();
$product->setProduct("Laptop", 850);
echo $product->displayProduct();
?>
Output:
Laptop costs $850
Here:
Productis the class.$productis the object.nameandpriceare properties.setProduct()anddisplayProduct()are methods.
The $this keyword refers to the current object instance inside the class.
You can read more about PHP classes and objects in the official PHP documentation at php.net.
Encapsulation in PHP
Encapsulation means protecting class data and controlling how it is accessed. Instead of allowing direct access to properties, you use methods to read or update them safely.
PHP provides three access modifiers:
public– accessible everywhereprotected– accessible inside the class and child classesprivate– accessible only inside the same class
Example:
<?php
class BankAccount
{
private $balance = 0;
public function deposit($amount)
{
if ($amount > 0) {
$this->balance += $amount;
}
}
public function getBalance()
{
return $this->balance;
}
}
$account = new BankAccount();
$account->deposit(500);
echo "Current Balance: $" . $account->getBalance();
?>
Output:
Current Balance: $500
In this example, the balance cannot be modified directly from outside the class because it is marked as private.
This prevents accidental changes and helps maintain data integrity.
Inheritance in PHP
Inheritance allows one class to reuse the properties and methods of another class.
The child class uses the extends keyword to inherit from the parent class.
<?php
class Animal
{
public function sound()
{
return "Animal sound";
}
}
class Dog extends Animal
{
public function sound()
{
return "Dog barks";
}
}
$dog = new Dog();
echo $dog->sound();
?>
Output:
Dog barks
Here, the Dog class inherits from the Animal class and overrides the sound() method.
Inheritance reduces repeated code and makes related classes easier to manage.
Abstraction in PHP
Abstraction means showing only the important functionality and hiding the internal implementation details.
In PHP, abstraction is commonly implemented using abstract classes and interfaces.
An abstract class cannot be instantiated directly. It is meant to act as a base class.
<?php
abstract class Payment
{
abstract public function processPayment($amount);
}
class CreditCardPayment extends Payment
{
public function processPayment($amount)
{
return "Processed credit card payment of $" . $amount;
}
}
$payment = new CreditCardPayment();
echo $payment->processPayment(120);
?>
Output:
Processed credit card payment of $120
The abstract class defines what must be implemented, but the child class decides how to implement it.
Polymorphism in PHP
Polymorphism allows different classes to use the same method name with different behavior.
This makes code flexible and easier to extend.
<?php
interface Shape
{
public function area();
}
class Circle implements Shape
{
private $radius;
public function __construct($radius)
{
$this->radius = $radius;
}
public function area()
{
return 3.14 * $this->radius * $this->radius;
}
}
class Rectangle implements Shape
{
private $width;
private $height;
public function __construct($width, $height)
{
$this->width = $width;
$this->height = $height;
}
public function area()
{
return $this->width * $this->height;
}
}
$shapes = [
new Circle(5),
new Rectangle(4, 6)
];
foreach ($shapes as $shape) {
echo $shape->area() . "<br>";
}
?>
Output:
78.5
24
Even though both classes use the same area() method name, each class calculates the result differently.
Interface and Trait in PHP
Interfaces and traits are also important parts of modern PHP OOP.
PHP Interface Example
An interface defines a contract that classes must follow.
<?php
interface Logger
{
public function log($message);
}
class FileLogger implements Logger
{
public function log($message)
{
return "Saving log: " . $message;
}
}
$logger = new FileLogger();
echo $logger->log("User logged in");
?>
Output:
Saving log: User logged in
Interfaces are useful when multiple classes should follow the same method structure.
PHP Trait Example
Traits allow you to reuse methods across multiple classes without inheritance.
<?php
trait Timestamp
{
public function getTimestamp()
{
return date("Y-m-d H:i:s");
}
}
class Order
{
use Timestamp;
}
$order = new Order();
echo $order->getTimestamp();
?>
Traits help avoid duplicate code when multiple unrelated classes need the same functionality.
Real-Time PHP OOP Example Project
The downloadable project included with this tutorial demonstrates a simple shopping cart system using PHP OOP concepts.
The project includes:
- Product class
- Cart class
- Inheritance example
- Interface usage
- Trait usage
- Encapsulation with private properties
The project is intentionally small and simple so intermediate PHP developers can understand the code flow easily.

PHP OOP concepts example project output
Common Errors in PHP OOP
While learning object-oriented programming in PHP, developers often run into a few common mistakes.
1. Accessing Private Properties Directly
The following code will cause an error because the property is private.
<?php
class User
{
private $name = "John";
}
$user = new User();
echo $user->name;
?>
Correct approach:
<?php
class User
{
private $name = "John";
public function getName()
{
return $this->name;
}
}
$user = new User();
echo $user->getName();
?>
2. Forgetting to Implement Interface Methods
If a class implements an interface, all required methods must be defined.
<?php
interface PaymentGateway
{
public function pay();
}
class StripePayment implements PaymentGateway
{
}
?>
This will produce a fatal error because the pay() method is missing.
3. Creating Objects from Abstract Classes
Abstract classes cannot be instantiated directly.
<?php
abstract class Vehicle
{
}
$vehicle = new Vehicle();
?>
Instead, create a child class and instantiate that child class.
Security Considerations
Even though OOP mainly focuses on code structure, secure coding practices are still important.
- Keep sensitive properties private whenever possible.
- Validate user input before assigning values to objects.
- Avoid exposing internal class data directly.
- Use type declarations in modern PHP projects for safer code.
- Do not store passwords directly inside objects without hashing.
If your OOP application interacts with a database, read this guide on preventing SQL injection in PHP.
Developer FAQ
Is OOP mandatory in PHP?
No. PHP supports both procedural programming and object-oriented programming. But OOP is better for medium and large applications.
What is the difference between a class and an object?
A class is a blueprint. An object is a real instance created from that class.
What is the use of traits in PHP?
Traits help reuse methods across multiple classes without using inheritance.
Does Laravel use PHP OOP?
Yes. Laravel is heavily based on object-oriented programming concepts like classes, interfaces, dependency injection, and traits.
Should beginners learn procedural PHP before OOP?
Learning basic procedural PHP first helps understand syntax and program flow. After that, learning OOP becomes much easier.
Download the Source Code
The downloadable project included with this tutorial demonstrates the core OOP concepts discussed above.
The project includes:
- Classes and objects
- Encapsulation using private properties
- Inheritance
- Interfaces
- Traits
- Polymorphism
You can run the project locally using PHP 8 or later.
How to Run the Project
- Download the ZIP file.
- Extract it into your local PHP server directory.
- Open the project folder in the browser.
- Run
index.php.
Conclusion
PHP supports all major object-oriented programming concepts needed to build structured and maintainable applications.
Classes and objects form the foundation. Encapsulation protects data. Inheritance helps reuse code. Abstraction simplifies implementation details. Interfaces and traits improve flexibility and reusability.
Once you start building larger PHP applications, OOP becomes extremely useful for organizing your code cleanly.
If you want to continue learning advanced PHP concepts, you can also read the PHP array guide at Power of PHP Arrays.
Best tutorial on the Internet, thanks.
Welcome Shindujah
Simple and easy to understand.
Thank you Gatamu.