PHP Access Modifiers

Ma Mahalakshmi V Updated 14 Nov 2026
6 min read ·Lesson 157 of 256

What Are Access Modifiers?

In simple terms: Access modifiers decide who is allowed to use a property, method, or constant of a class. Some parts are meant for everyone, some only for the class itself, and some for the class and its child classes. They work like the rooms of a shop: the showroom is open to customers, the stockroom only to staff, and the safe only to the owner.

Technically: PHP has three visibility levels — public, protected, and private — which apply to properties, methods, and (since PHP 7.1) class constants. Visibility is checked at runtime based on the class scope of the code trying to access the member. PHP 8.4 adds asymmetric visibility for properties (separate read and write visibility; see Asymmetric Visibility (PHP 8.4)).


The Three Visibility Levels

ModifierAccessible From the Class ItselfFrom Child ClassesFrom Outside
public✔✔✔
protected✔✔✘
private✔✘✘

Example

<?php
class Employee
{
    public string $name;
    protected string $department;
    private float $salary;

    public function __construct(string $name, string $department, float $salary)
    {
        $this->name = $name;
        $this->department = $department;
        $this->salary = $salary;
    }

    public function annualSummary(): string
    {
        return sprintf('%s (%s): bonus ₹%s', $this->name, $this->department, number_format($this->calculateBonus(), 2));
    }

    private function calculateBonus(): float
    {
        return $this->salary * 0.10;
    }
}

$employee = new Employee('Asha', 'Engineering', 1_200_000);

echo $employee->name . "\n";
echo $employee->annualSummary() . "\n";

$attempts = [
    'protected property' => fn() => $employee->department,
    'private property' => fn() => $employee->salary,
    'private method' => fn() => $employee->calculateBonus(),
];

foreach ($attempts as $label => $attempt) {
    try {
        $attempt();
    } catch (Error $e) {
        echo "$label: " . $e->getMessage() . "\n";
    }
}

Output

Asha
Asha (Engineering): bonus ₹120,000.00
protected property: Cannot access protected property Employee::$department
private property: Cannot access private property Employee::$salary
private method: Call to private method Employee::calculateBonus() from global scope

How It Works

  1. name and annualSummary() are public: any code can use them.
  2. Inside the class, annualSummary() can freely use the protected department, the private salary, and the private calculateBonus() — all members are accessible within their own class.
  3. From outside the class (here, closures defined in the global scope), protected and private members are rejected with an Error.

The salary and the bonus formula are internal details. Outside code can only ask for the summary, so the formula can change later without breaking any caller.


protected: Shared With Child Classes

Protected members are available in classes that extend the class (see PHP Inheritance), but not to outside code:

<?php
class Report
{
    public function __construct(protected string $title) {}

    public function render(): string
    {
        return $this->header() . "\n" . $this->body();
    }

    protected function header(): string
    {
        return "=== {$this->title} ===";
    }

    protected function body(): string
    {
        return '(empty report)';
    }
}

class SalesReport extends Report
{
    public function __construct(private array $sales)
    {
        parent::__construct('Sales Report');
    }

    protected function body(): string
    {
        $lines = [];
        foreach ($this->sales as $region => $amount) {
            $lines[] = "$region: ₹" . number_format($amount);
        }
        return implode("\n", $lines);
    }
}

echo (new SalesReport(['Chennai' => 420000, 'Madurai' => 185000]))->render() . "\n";

Output

=== Sales Report ===
Chennai: ₹420,000
Madurai: ₹185,000
  • SalesReport uses the protected title (via the inherited header()) and overrides the protected body() method.
  • Outside code can only call render(); it cannot call header() or body() directly.
  • sales is private to SalesReport; even the parent Report cannot access it.

Note that private members of a parent class are not visible in child classes. If SalesReport tried to read a private property of Report, PHP would treat it as an undefined property of SalesReport. Use protected only for members that child classes are meant to use or override.


Visibility Is Per Class, Not Per Object

Code inside a class can access the private members of other objects of the same class:

<?php
final class Money
{
    public function __construct(private int $paise) {}

    public function equals(Money $other): bool
    {
        return $this->paise === $other->paise;   // allowed: same class
    }

    public function isGreaterThan(Money $other): bool
    {
        return $this->paise > $other->paise;
    }
}

$a = new Money(129900);
$b = new Money(129900);
$c = new Money(50);

var_dump($a->equals($b));
var_dump($c->isGreaterThan($a));

Output

bool(true)
bool(false)

Visibility protects the class's implementation from outside code. Objects of the same class share that implementation, so they may access each other's internals — which makes methods like equals() possible without exposing the value publicly.


Visibility of Class Constants

<?php
class PaymentGateway
{
    public const CURRENCY = 'INR';
    private const API_VERSION = '2026-01';

    public function endpoint(): string
    {
        return 'https://api.example.com/' . self::API_VERSION . '/payments';
    }
}

echo PaymentGateway::CURRENCY . "\n";
echo (new PaymentGateway())->endpoint() . "\n";

try {
    echo PaymentGateway::API_VERSION;
} catch (Error $e) {
    echo $e->getMessage() . "\n";
}

Output

INR
https://api.example.com/2026-01/payments
Cannot access private constant PaymentGateway::API_VERSION

Constants without a modifier are public. Private constants keep implementation details out of the class's public API.


Default Visibility

MemberWithout a Modifier
Methodspublic
Constantspublic
PropertiesA modifier (or var, an old synonym for public) is required

Although methods default to public, always write the modifier explicitly; coding standards require it, and it shows that the choice was deliberate.


Choosing the Right Visibility

A good rule: start with private and widen visibility only when there is a reason.

SituationVisibility
Part of the class's purpose, used by other codepublic
An extension point that child classes should override or useprotected
Internal state and helper methodsprivate
Value others may read but must not changepublic readonly (or public private(set) in PHP 8.4)

Why Narrow Visibility Helps

  • Freedom to change: Private members can be renamed, removed, or reimplemented without affecting other code.
  • Data integrity: State can only change through methods that enforce the rules.
  • Smaller public API: Users of the class see only what they need, which makes the class easier to understand.

protected members are part of the contract with child classes, so changing them can break subclasses — treat them almost as carefully as public members.


Common Mistakes

Making Everything Public

Effect: Any code can modify the object's state, bypassing validation.

Fix: Keep properties private; expose behavior through methods.

Using protected "Just in Case"

Effect: Internal details become part of the API for subclasses and are hard to change later.

Fix: Use private until a real subclass needs access.

Expecting Child Classes to Access Private Parent Members

Effect: Undefined property warnings or errors in the child class.

Fix: Make the member protected, or provide a protected/public accessor method in the parent.

Relying on Visibility for Security

Effect: Visibility organizes code; it does not protect secrets from someone who can run code in your application (reflection and serialization can still access private data).

Fix: Protect secrets with proper storage, permissions, and encryption.


Best Practices

  • Declare visibility explicitly on every property, method, and constant.
  • Default to private; use protected for deliberate extension points; use public for the class's intended API.
  • Prefer public readonly over public mutable properties for data that should be visible.
  • Keep the public API small and focused.
  • Use visibility to protect invariants, not as a security mechanism.

Official reference: https://www.php.net/manual/en/language.oop5.visibility.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Tutorial Index PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about PHP Access Modifiers and get answers drawn from it.

Signed-in readers only.