PHP Access Modifiers: How Public, Private & Protected Work

php access modifiers

PHP supports OOP with access modifiers to prevent unintended changes and improve security. In this article, we will cover the following topics:

  • What is the definition of access modifiers, and why are they important?
  • Access modifier types and use them in the inheritance and encapsulation examples.
  • The difference between their three types.

Let’s start with what access modifiers are.

Understand What Access Modifiers Are in PHP

The PHP Access modifiers control how properties and methods are accessed within a class. They define whether code outside the class can use them directly.

They are important for object-oriented programming (OOP). Here’s why they matter:

  • Encapsulation – They protect internal class data from unintended modification by restricting direct access.
  • Data security – Private and protected modifiers prevent unauthorized changes. They reduce the risk of bugs.
  • Code maintainability – They help manage dependencies and make code easier to update and refactor with limited access.
  • Inheritance control – They define how subclasses interact with parent class properties and methods, and ensure proper structure.

Let’s move on to the following section to understand the types of access modifiers in-depth.

Types of Access Modifiers in PHP

Access modifiers in PHP define the visibility of class properties and methods. There are three types:

  • Public modifier.
  • Private modifier.
  • Protected modifier.

Let’s take each one in detail with an example.

Public Modifier

The public access modifier allows class properties and methods to be accessed from anywhere:

  • Inside the class.
  • In subclasses
  • Outside the class.

This means there are no restrictions on visibility.

Here is an example:

class Individual {
   // Public property
    public $name = "FlatCoding"; 

    public function greet() {
        return " Hello, " . $this->name;
    }
}

$individual = new Individual();
echo $individual->name;
echo $individual->greet();

Here is the output:

FlatCoding Hello, FlatCoding

So, when to use a public modifier?

  • When a property or method needs to be accessed freely across the application.
  • For utility methods that don’t modify sensitive data.
  • With designed APIs or libraries where external access is required.

Private Modifier

The private access modifier limits access to properties and methods.It makes them only accessible within the same class.

The other classes and included subclasses cannot access private members, even if they extend the class.

This makes sure that internal details are kept hidden from outside interaction and promotes better encapsulation.

Here is an example:

class Viewer {
    // Private property
    private $password = "secret"; 

    private function encryptPassword() {
        return md5($this->password);
    }

    public function showPassword() {
        // Access private method within the same class
        return $this->encryptPassword(); 
    }
}

$viewer = new Viewer();

Here, if you use the property $viewer->password; or the method $viewer->encryptPassword(); it will show you an error such as:

echo $viewer->password;
echo $viewer->encryptPassword();

Here is the output:

Error: Cannot access private property
Error: Cannot access private method

Hence, you need to use a public function inside the same class to access the private method or property like the below:

echo $viewer->showPassword();

Output:

5ebe2294ecd0e0f08eab7690d2a6ee69

You use this when:

  • You want to hide implementation details and prevent external code from modifying the internal state.
  • For sensitive data like passwords, internal calculations, or any logic that shouldn’t be altered from the outside.
  • When you need to protect certain functionality, you need to make sure it’s only manipulated by the class itself.

Protected Modifier

The protected access modifier allows properties and methods to be accessed within the same class and by subclasses, but not from outside the class.

This creates a balance between public and private access. It works well when you want child classes to use specific data or methods, but still keep them hidden from external use.

Here is an example:

class Guest {
    // Protected property
    protected $username = "guest123"; 
    protected function getUsername() {
        return $this->username;
    }
}

class Admin extends Guest {
    public function displayUsername() {
        // Access protected method in subclass
        return $this->getUsername(); 
    }
}

$guest = new Admin();

If you try to access the $guest->username; it will cause an error for example:

echo $guest->username;  

Here is the output:

Error: Cannot access protected property

It works when you use the subclass. The subclass can access the data or methods, but they remain hidden from outside use. Here is an example:

// The subclass
echo $guest->displayUsername(); 

Here is the output:

guest123

So, you use a protected modifier in the following cases:

  • When you want to allow access to a class’s properties or methods within the class and its subclasses, but prevent external code from accessing them.
  • For functionality that’s shared or extended by child classes but shouldn’t be accessed directly by other parts of the program.
  • When creating base classes that provide common functionality to derived classes, but need to hide details from the outside world.

Let’s move on to the following section to understand the difference between access modifier types.

Difference Between Public, Private, and Protected

Each modifier provides a different level of access. Here are the key differences:

ModifierVisibilityAccess LevelUse Case
PublicAccessible from anywhereCan be accessed from the same class, subclasses, and outside the class.Use when you want properties or methods to be widely accessible, like API methods or utilities.
PrivateAccessible only within the classOnly accessible within the same class, not even in subclasses.Use for sensitive data or internal methods you don’t want to expose or change outside the class.
ProtectedAccessible within the class and subclassesIt can be accessed from the same class, subclasses, and outside the class.Use for properties or methods that need to be accessible to child classes but should remain hidden from external access.

Wrapping Up

Access modifiers help you to control how properties and methods are accessed. They help you in:

  • Maintain security.
  • Improve code organization.
  • It ensures better encapsulation.

Here are the types of access modifiers:

  • Public – Allows access from anywhere. Use it when properties or methods need to be freely accessible.
  • Private – Restricts access to within the class. Best for sensitive data and internal logic.
  • Protected – Allows access within the class and subclasses but prevents external use. Useful for inheritance.

FAQ’s

What are access modifiers in PHP?

Access modifiers control the visibility of class properties and methods. They determine whether code outside the class can access them.

Why are access modifiers important in PHP?

Access modifiers help protect data, improve code organization, and prevent unintended modifications. They enforce encapsulation, enhance security, and make code easier to maintain.

What are the types of access modifiers in PHP?

PHP has three access modifiers:
  • Public – Accessible from anywhere.
  • Private – Accessible only within the same class.
  • Protected – Accessible within the same class and its subclasses.

How do public, private, and protected modifiers differ in PHP?

  • Public allows access from anywhere.
  • Private restricts access to within the class only.
  • Protected allows access within the class and its subclasses but prevents access from outside.

When should you use each access modifier in PHP?

  • Use public when a property or method needs to be accessible anywhere.
  • Use private for sensitive data or internal logic that should not be accessed outside the class.
  • Use protected when a property or method should be available to subclasses but hidden from external code.

Similar Reads

PHP MySQL LIMIT Data: How to Optimize PHP Queries?

There are situations where you only need a specific number of rows returned. This is where the "LIMIT" clause in…

PHP array_combine: How to Merge Arrays as Key and Value

The array_combine function in PHP creates a new array with one array for keys and another for values. It needs…

PHP $_FILES: How to Upload Files in PHP

The PHP superglobal $_FILES is a very important utility and great for dealing with file uploads on the web. When a user…

PHP array_map Function: How to Transform Arrays with Examples

PHP added the array_map() function to help you apply one function to each item in an array. Understand the array_map…

Abstract Class in PHP: How It Works & Examples

Abstract class in PHP appeared to provide a way to define a structure for related classes and don't allow direct…

PHP Variable Basics: Everything You Need to Know

Think about the PHP variable as little storage boxes holding your data, whether it is a number, a word, or…

PHP array_diff_ukey Function: How it Works with Examples

The PHP array_diff_ukey function compares keys in two or more arrays. It returns the keys from the first array that…

filter_has_var Function: Check if Input Exists in PHP

User input does not always come through as expected. Sometimes values are missing or not set at all. This can…

PHP array_merge: Combine Multiple Arrays into One

You have two or more arrays. You want one. That is the problem array_merge solves in PHP. This function lets…

PHP array_keys: How to Extract Keys in Arrays with Examples

This guide shows how PHP array_keys finds all keys in an array and how you can filter them by a…

Previous Article

PHP OOP Constructor: How It Works in a Class with Examples

Next Article

Abstract Class in PHP: How It Works & Examples

Write a Comment

Leave a Comment

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


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.