PHP Access Modifiers

Yo Yogesh.M Updated 17 Oct 2026
6 min read ·Lesson 64 of 109
In this post

PHP Access Modifiers 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

PHP Access Modifiers

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 Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement 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 PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else Slicing Strings User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators
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.