PHP OOP Basics
Easy PHP OOP Basics Guide: 4 Core Principles & Examples
Master Object-Oriented Programming with this complete PHP OOP basics guide. Learn classes, objects, inheritance, encapsulation, polymorphism, and abstraction.
Estimated Read Time: 21 Minutes | Category: PHP Web Development
Overview: Understanding PHP OOP Basics & Object-Oriented Architecture
Quick PHP OOP Basics Summary:
- Object-Oriented Paradigm: Object-Oriented Programming (OOP) organizes software code into reusable, self-contained structures called Classes and Objects, replacing procedural global scripts.
- Classes vs. Objects: A Class is a blueprint defining properties and methods, while an Object is an active instance of that class allocated in server memory.
- Visibility Access Modifiers: Controls property and method access levels using
public(accessible everywhere),protected(accessible in class and subclasses), andprivate(accessible strictly inside the defining class). - 4 Pillar Principles: OOP is built on Encapsulation (data hiding), Inheritance (code reuse via
extends), Polymorphism (interface overriding), and Abstraction (hiding implementation details). - Constructor Lifecycle: The
__construct()magic method automatically initializes object properties when a new object instance is created.
Welcome to Lesson 22 of our structured web development course, marking the final master lesson in our complete curriculum roadmap. Following our previous tutorial on Easy PHP CRUD Operations Guide: 4 Secure Database Actions, you now understand how to execute secure Create, Read, Update, and Delete database operations using PDO. The final milestone in professional backend engineering is mastering PHP OOP basics.
In early web development, procedural programmingβwriting linear functions and global scriptsβwas common. However, as web applications grow into enterprise software (like WordPress, Laravel, or Symfony), procedural code becomes difficult to maintain, test, and scale. Object-Oriented Programming organizes complex backend systems into modular, reusable components that model real-world entities.
In this comprehensive PHP OOP basics tutorial, we will explore classes, objects, access modifiers, constructors/destructors, inheritance, method overriding, encapsulation, interfaces, abstract classes, and production-level OOP code examples.

Prerequisites Before Learning Object-Oriented PHP
To test the hands-on code examples in this PHP OOP basics guide, verify that your development environment meets these basic requirements:
- Active Web Server: Running installation of Apache or Nginx with PHP 8.x+ (configured via XAMPP, Homebrew, or Terminal).
- Code Editor: A modern IDE such as Visual Studio Code or PhpStorm.
- Foundational Knowledge: Solid understanding of PHP variables, functions, data types, and PDO database connections.
If you need to review how functions process data parameters before learning class methods, visit our previous guide on Easy PHP Functions Guide: 5 Core Concepts & Examples.
1. Classes and Objects: The Core Foundation
The foundation of PHP OOP basics rests on two core concepts:
- Class: A user-defined template or blueprint that defines state properties (variables) and behaviors (functions/methods).
- Object: A concrete instance created from a class template using the
newkeyword.
Class & Object Syntax Example
<?php
declare(strict_types=1);
// Defining a User Class Blueprint
class User {
// Class Properties (Variables)
public string $username;
public string $email;
// Class Method (Function)
public function getProfileSummary(): string {
return "User Profile: {$this->username} ({$this->email})";
}
}
// Instantiating Objects from the User Class
$user1 = new User();
$user1->username = "alex_mercer";
$user1->email = "alex@phponline.in";
$user2 = new User();
$user2->username = "sarah_connor";
$user2->email = "sarah@phponline.in";
echo $user1->getProfileSummary() . "<br>";
echo $user2->getProfileSummary();
?>Want to test this code live? Try running it in our PHP Online Compiler.
2. Constructor Lifecycle & Property Promotion
A constructor is a special magic method named __construct(). PHP automatically executes this method when an object is instantiated with new, making it ideal for setting initial property values.
Modern Constructor Property Promotion (PHP 8.0+)
PHP 8.0 introduced Constructor Property Promotion, allowing you to combine property declarations and constructor assignments into a single line header:
<?php
declare(strict_types=1);
class Product {
// PHP 8 Constructor Property Promotion (declares & assigns in one step)
public function __construct(
public int $id,
public string $title,
public float $price,
public bool $inStock = true
) {}
public function getFormattedPrice(): string {
return "$" . number_format($this->price, 2);
}
}
// Instantiating object with constructor parameters
$laptop = new Product(101, "Developer Laptop", 1299.99);
echo "Product: " . $laptop->title . " β Price: " . $laptop->getFormattedPrice();
?>Want to test this code live? Try running it in our PHP Online Compiler.
3. Property Visibility: Public, Protected, and Private
Access modifiers control where class properties and methods can be accessed or modified from:
| Access Modifier | Inside Defining Class | Inside Child Classes (Subclasses) | Outside Class Scope |
|---|---|---|---|
public | Yes | Yes | Yes (Unrestricted access) |
protected | Yes | Yes (via extends) | No (Causes Fatal Error) |
private | Yes | No | No (Encapsulated strictly inside defining class) |
4. The 4 Fundamental Pillars of PHP OOP
Pillar 1: Encapsulation (Data Hiding)
Encapsulation restricts direct external access to an object’s internal properties by making them private or protected. Data is accessed or modified safely through public getter and setter methods that enforce validation rules:
<?php
class BankAccount {
private float $balance = 0.0;
// Getter method
public function getBalance(): float {
return $this->balance;
}
// Setter method with validation logic
public function deposit(float $amount): void {
if ($amount > 0) {
$this->balance += $amount;
} else {
throw new Exception("Deposit amount must be positive!");
}
}
}
$account = new BankAccount();
$account->deposit(250.00);
echo "Current Account Balance: $" . number_format($account->getBalance(), 2);
?>Want to test this code live? Try running it in our PHP Online Compiler.
Pillar 2: Inheritance (Code Reuse via ‘extends’)
Inheritance allows a child class (subclass) to inherit all public and protected properties and methods from a parent class using the extends keyword:
<?php
// Parent Class
class Employee {
public function __construct(
protected string $name,
protected float $salary
) {}
public function getDetails(): string {
return "Employee: {$this->name}, Salary: $" . number_format($this->salary, 2);
}
}
// Child Class inheriting from Employee
class Developer extends Employee {
public function __construct(
string $name,
float $salary,
public string $primaryLanguage
) {
// Call parent constructor
parent::__construct($name, $salary);
}
// Method Extension
public function getDeveloperInfo(): string {
return $this->getDetails() . " (Specialty: {$this->primaryLanguage})";
}
}
$dev = new Developer("Alex Mercer", 85000.00, "PHP/Laravel");
echo $dev->getDeveloperInfo();
?>Want to test this code live? Try running it in our PHP Online Compiler.
Pillar 3: Polymorphism (Method Overriding)
Polymorphism allows different child classes to override a parent method and provide specialized behavior while sharing the same method name:
<?php
abstract class Shape {
abstract public function calculateArea(): float;
}
class Circle extends Shape {
public function __construct(private float $radius) {}
public function calculateArea(): float {
return pi() * ($this->radius ** 2);
}
}
class Square extends Shape {
public function __construct(private float $side) {}
public function calculateArea(): float {
return $this->side * $this->side;
}
}
$shapes = [new Circle(5.0), new Square(4.0)];
foreach ($shapes as $shape) {
echo "Area: " . round($shape->calculateArea(), 2) . "<br>";
}
?>Want to test this code live? Try running it in our PHP Online Compiler.
Pillar 4: Abstraction (Interfaces & Abstract Classes)
Abstraction enforces a structural contract without defining full internal implementation. An interface defines method signatures that implementing classes must define:
<?php
// Defining an Interface Contract
interface PaymentGatewayInterface {
public function processPayment(float $amount): bool;
}
class StripeGateway implements PaymentGatewayInterface {
public function processPayment(float $amount): bool {
echo "Processing $" . $amount . " payment via Stripe API...<br>";
return true;
}
}
class PayPalGateway implements PaymentGatewayInterface {
public function processPayment(float $amount): bool {
echo "Processing $" . $amount . " payment via PayPal API...<br>";
return true;
}
}
// Payment Processor receiving any class implementing PaymentGatewayInterface
function checkout(PaymentGatewayInterface $gateway, float $total) {
$gateway->processPayment($total);
}
checkout(new StripeGateway(), 149.99);
checkout(new PayPalGateway(), 89.50);
?>Want to test this code live? Try running it in our PHP Online Compiler.
Summary Comparison: Procedural vs. Object-Oriented PHP
| Feature / Criteria | Procedural PHP | Object-Oriented PHP (OOP) |
|---|---|---|
| Core Focus | Sequential functions acting on global data variables. | Objects encapsulating state data and behavior methods together. |
| Code Reusability | Low (requires copying functions or files). | High (leveraging Inheritance and Interfaces). |
| Data Security | Low (global variables can be altered unexpectedly). | High (Encapsulation hides private properties). |
| Maintenance & Scaling | Difficult on large enterprise applications. | Ideal for enterprise applications and modern frameworks. |
Troubleshooting Common PHP OOP Errors
| Observed Error / Exception | Probable Cause | Recommended Solution |
|---|---|---|
Fatal error: Cannot access private property... | Attempting to read or write a private or protected property directly outside the defining class. | Use public getter/setter methods (e.g., $obj->getBal()) or change visibility to public. |
Fatal error: Class ... contains 1 abstract method and must be declared abstract | A class extending an abstract class or implementing an interface failed to define required abstract methods. | Implement all required interface/abstract methods inside the child class body. |
Error: Using $this when not in object context | Attempting to reference $this inside a static class method. | Static methods belong to the class itself, not instances; use self::$property instead of $this. |
Fatal error: Uncaught Error: Cannot instantiate interface... | Attempting to create an object directly from an interface or abstract class (e.g., new InterfaceName()). | Instantiate a concrete child class that implements the interface or extends the abstract class instead. |
Frequently Asked Questions (FAQ)
Q1: What are PHP OOP basics and why is Object-Oriented Programming used?
PHP OOP basics refer to Object-Oriented Programming principles where code is organized into reusable Classes and Objects rather than linear procedural functions. OOP improves code reusability, enhances data security via encapsulation, and is required by modern PHP frameworks like Laravel and Symfony.
Q2: What is the difference between a class and an object in PHP?
A class is a user-defined blueprint or template that defines properties and methods. An object is an active instance of that class allocated in server memory using the new keyword (e.g., $user = new User();).
Q3: What is the difference between public, protected, and private visibility?
public properties and methods are accessible from anywhere. protected members are accessible only within the defining class and its child subclasses (via extends). private members are accessible strictly inside the defining class itself.
Q4: What is the difference between an interface and an abstract class in PHP?
An interface defines method signatures without any method bodies, acting as a strict structural contract. An abstract class can contain both abstract method signatures and fully implemented concrete methods with properties that child classes inherit.
Course Completion & Official References
Congratulations on completing our entire structured PHP tutorial series! You now possess comprehensive backend engineering skills spanning basic syntax, dynamic web forms, database integration, security, and Object-Oriented architecture.
Consult official technical standards on the PHP Official Object-Oriented Programming Manual (php.net).
Return to Course Index: Revisit previous modules or review lessons from the beginning: Course Homepage: Best PHP Tutorial for Beginners β
# Summary
Here is what you've learned in this lesson:
- Easy PHP OOP Basics Guide: 4 Core Principles & Examples
- Overview: Understanding PHP OOP Basics & Object-Oriented Architecture
- Prerequisites Before Learning Object-Oriented PHP
- 1. Classes and Objects: The Core Foundation
- 2. Constructor Lifecycle & Property Promotion
- 3. Property Visibility: Public, Protected, and Private
- 4. The 4 Fundamental Pillars of PHP OOP
- Summary Comparison: Procedural vs. Object-Oriented PHP
- Troubleshooting Common PHP OOP Errors
- Frequently Asked Questions (FAQ)
- Course Completion & Official References
Continue to the next lesson and learn more about PHP Strings.
