Access Modifiers in PHP (public, private, protected)

Introduction

Access modifiers in PHP control how properties and methods can be accessed inside Object-Oriented Programming (OOP). They help define the visibility of class members and protect important data from unwanted access.

With access modifiers, you can decide who can access a property, who can call a method, and whether a value should be changed from outside the class or only within the class itself.

PHP provides three main access modifiers: public, private, and protected. Each one has a different level of access and is used based on the security and structure of your application.

Understanding access modifiers is important because they help you write safer, cleaner, and more professional OOP code, especially in real-world projects like WordPress plugins, custom PHP applications, and large frameworks.

Why Are Access Modifiers Important?

Without access control, anyone could change the internal data of an object. This could lead to unexpected behavior and security problems.

Access modifiers help you:

  • Protect sensitive data
  • Control how properties are accessed
  • Prevent accidental changes
  • Follow proper OOP principles
  • Implement encapsulation

They make your code safer and more professional.

Public Access Modifier

What is public?

  • Accessible from anywhere
  • Can be used inside and outside the class

Public Example

<?php
class User {
    public $name;

    public function setName($name) {
        $this->name = $name;
    }
}
?>

Accessing Public Members

<?php
$user = new User();
$user->name = "Divyesh";
$user->setName("Divyesh");
?>

✔ Works fine
✔ No restriction

Private Access Modifier

What is private?

  • Accessible only inside the same class
  • Cannot be accessed from outside or child classes

Used to hide sensitive data.

Private Example

<?php
class User {
    private $password;

    public function setPassword($pass) {
        $this->password = $pass;
    }
}
?>

Trying to Access Private Property

<?php
$user = new User();
$user->password = "123456"; //  Error
?>

❌ This will cause an error because $password is private.

Correct Way (Using Method)

<?php
$user->setPassword("123456");
?>

✔ Secure access

Why Private is Important (Encapsulation)

Encapsulation means hiding internal details and allowing access only through controlled methods.

For example:

  • You should not allow users to directly change account balance
  • Instead, provide deposit() and withdraw() methods

This prevents invalid or harmful data changes.

Protected Access Modifier

What is protected?

  • Accessible inside the class
  • Accessible in child (inherited) classes
  • Not accessible from outside

Protected Example

<?php
class User {
    protected $role = "User";
}
?>

Child Class Access

<?php
class Admin extends User {
    public function getRole() {
        return $this->role;
    }
}

$admin = new Admin();
echo $admin->getRole();
?>

✔ Works because role is protected.

Outside Access

<?php
$admin = new Admin();
echo $admin->role; //  Error
?>

❌ Not allowed

Difference Between Access Modifiers

ModifierSame ClassChild ClassOutside Class
public
protected
private

Why Access Modifiers Matter

They help you:

  • Prevent accidental data modification
  • Secure sensitive information
  • Control how your class is used
  • Follow encapsulation principle

Real-World Analogy

Think of a company:

  • Public → Information available to everyone
  • Private → Personal data accessible only by the owner
  • Protected → Data accessible within the company hierarchy

This is how access control works in OOP as well.

Common Beginner Mistakes

  • Forgetting to declare visibility (PHP requires it)
  • Trying to access private properties directly
  • Confusing protected with private
  • Not using getter and setter methods
  • Making everything public

A good practice is:
👉 Keep properties private
👉 Use public methods to control access

Practical Task

Create a class named BankAccount:

  • Add a private property called balance
  • Create a public method to deposit money
  • Create a public method to withdraw money
  • Try accessing balance directly and observe what happens

This will help you understand access control better.

Summary

  • Access modifiers control visibility in PHP classes
  • public allows access everywhere
  • private allows access only inside the class
  • protected allows access inside the class and child classes
  • They help implement encapsulation and protect data

Access modifiers are essential for writing secure and structured OOP code.

In the next tutorial, we’ll learn about Inheritance in PHP.

Related Tutorials

  • OOP in PHP – Introduction to Object-Oriented Programming

    Introduction As PHP projects become larger, managing code using only procedural programming becomes difficult. Files get longer, functions become harder to track, and updating the project takes more time. This is where Object-Oriented Programming (OOP) becomes important. OOP helps developers organize code in a cleaner and more structured way by grouping related data and functionality…

  • Classes & Objects in PHP

    Introduction In Object-Oriented Programming (OOP), classes and objects are the foundation of everything. Once you understand these two concepts clearly, learning advanced OOP topics like constructors, inheritance, and polymorphism becomes much easier. In simple words, a class is a blueprint, and an object is a real instance created from that blueprint. For example, if “Car”…

  • Constructors & Destructors in PHP

    Introduction In Object-Oriented Programming (OOP), constructors and destructors are special methods that automatically run at specific moments in an object’s lifecycle. A constructor runs when an object is created, while a destructor runs when an object is destroyed. These methods help developers manage object initialization and cleanup efficiently. Instead of manually setting values after creating…

  • Inheritance in PHP

    Introduction Inheritance is one of the most important concepts in Object-Oriented Programming (OOP). It allows one class to inherit the properties and methods of another class. In simple words, inheritance helps you reuse existing code instead of rewriting it. This makes your code cleaner, more structured, and easier to maintain. In this tutorial, you will…

  • Encapsulation in PHP

    Introduction Encapsulation is one of the core principles of Object-Oriented Programming (OOP). It refers to the concept of restricting direct access to certain parts of an object and allowing controlled access through methods. In simple words, encapsulation means data hiding. Instead of allowing users to directly access and modify object properties, we protect them using…

  • Polymorphism in PHP

    Introduction Polymorphism is one of the four core principles of Object-Oriented Programming (OOP): The word Polymorphism means “many forms.” In PHP, polymorphism allows different classes to use the same method name but perform different actions. This makes your code flexible, scalable, and easier to maintain. 📌 What is Polymorphism? Polymorphism allows objects of different classes…

Leave a Reply

Your email address will not be published. Required fields are marked *