OOP With PHP 2: Encapsulation & Access Control In PHP

Object Oriented Programming PHP
Profile Picture Joton Sutradharβ€’ πŸ“– 4 min read β€’ πŸ“… 2nd February 2025

Heads up!

Check my blogs on Dev.to and Medium!

Introduction

Encapsulation is one of the core principles of Object-Oriented Programming (OOP) in PHP. It ensures that an object's internal data is protected from unintended modifications and allows controlled access through defined methods. This concept is implemented using Access Modifiers such as public, private, and protected, which control how properties and methods can be accessed.

 

In this blog, we will cover:

  • Understanding Access Modifiers in PHP

  • Encapsulation: Data Hiding and Control

  • Practical Examples of Encapsulation in PHP

By the end of this article, you'll understand how to use encapsulation effectively to write secure and maintainable code in PHP.

 

Access Modifiers in PHP

Access modifiers define the visibility of class properties and methods. PHP provides three types of access modifiers:

 

1. Public

  • Properties and methods declared as public can be accessed from anywhere, both inside and outside the class.

Example:

class User {
    public $name; // Public property
    
    public function sayHello() {
        return "Hello, my name is " . $this->name;
    }
}

$user = new User();
$user->name = "John";
echo $user->sayHello(); // Outputs: Hello, my name is John

 

2. Private

  • Properties and methods declared as private can only be accessed within the same class. They are not accessible from outside the class or in derived classes.

Example:

class BankAccount {
    private $balance = 1000; // Private property
    
    private function getBalance() {
        return $this->balance;
    }
    
    public function showBalance() {
        return "Your balance is: " . $this->getBalance();
    }
}

$account = new BankAccount();
echo $account->showBalance(); // Outputs: Your balance is: 1000

// The following line will cause an error
// echo $account->balance; // Fatal Error: Cannot access private property

 

3. Protected

  • Properties and methods declared as protected can only be accessed within the same class and by subclasses (child classes). They are not accessible from outside the class.

Example:

class Animal {
    protected $species;
    
    public function setSpecies($species) {
        $this->species = $species;
    }
}

class Dog extends Animal {
    public function getSpecies() {
        return "This is a " . $this->species;
    }
}

$dog = new Dog();
$dog->setSpecies("Dog");
echo $dog->getSpecies(); // Outputs: This is a Dog

// The following line will cause an error
// echo $dog->species; // Fatal Error: Cannot access protected property

 

Encapsulation in PHP: Data Hiding and Control

Encapsulation allows for better data security by preventing direct modification of sensitive properties. Instead, properties are accessed and modified through getter and setter methods.

Encapsulation Example:

class Employee {
    private $salary;
    
    public function setSalary($amount) {
        if ($amount > 0) {
            $this->salary = $amount;
        } else {
            echo "Invalid salary amount!";
        }
    }
    
    public function getSalary() {
        return $this->salary;
    }
}

$emp = new Employee();
$emp->setSalary(5000);
echo "Employee salary: " . $emp->getSalary(); // Outputs: Employee salary: 5000

 

In the above example:

  • The salary property is private, meaning it cannot be accessed directly.

  • The setSalary() method ensures that only positive values can be assigned to the salary.

  • The getSalary() method allows controlled access to the salary value.

 

Conclusion

Encapsulation is a crucial OOP concept that enhances data security and code maintainability. By using access modifiers (public, private, protected), developers can effectively control access to class properties and methods. Implementing encapsulation through getter and setter methods ensures that data remains secure and is modified only through controlled mechanisms.

By mastering encapsulation, you can write PHP applications that are more structured, secure, and scalable.

Stay tuned for more PHP OOP tutorials! πŸš€

Related Blogs
Clean Code, Scalable Systems: The Abstract Service Advantage In Laravel
PHP Laravel Abstraction Abstract Service Joton Sutradhar

Alright, Laravel developers, let's talk shop. We love Laravel for its elegance, convention over configuration, and how quickly it lets us build. But as our applications grow, even in a framework as opinionated as Laravel, we can fall into traps: repeating the same logic across different "service" classes, inconsistent data handling, or struggling to manage complex workflows.

Profile Picture Joton Sutradhar β€’ πŸ“– 17 min read β€’ πŸ“… 20th June 2025
The Art Of Debugging: Why It Matters And How To Master It πŸš€
Debugging PHP Web Development Programming Code Quality Error Handling Xdebug Troubleshooting

Debugging is one of the most crucial skills every developer must master, yet it's often overlooked in formal education. Whether you're a beginner writing your first "Hello World" program or a seasoned developer working on complex enterprise applications, debugging will be your constant companion throughout your coding journey.

Profile Picture Joton Sutradhar β€’ πŸ“– 11 min read β€’ πŸ“… 9th June 2025
Supercharge Your Laravel App With Queues – A Developer’s Experience With Background Email Sending
Laravel Jobs Queue Queue Jobs Php Joton Sutradhar

As Laravel developers, one of the critical lessons we eventually learn is: not everything should happen in real-time. Whether it's sending emails, processing images, syncing third-party data, or running analytics β€” pushing these resource-heavy or time-consuming tasks to the background is essential for a performant and responsive application.

Profile Picture Joton Sutradhar β€’ πŸ“– 6 min read β€’ πŸ“… 29th May 2025
Subscribe to my newsletter

Get recent projects & blog updates to your inbox.

I never share your email. Read our privacy policy.

© 2025 Joton Sutradhar. All rights reserved.