PHP Access Modifiers
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
| Modifier | Accessible From the Class Itself | From Child Classes | From 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
nameandannualSummary()are public: any code can use them.- Inside the class,
annualSummary()can freely use the protecteddepartment, the privatesalary, and the privatecalculateBonus()— all members are accessible within their own class. - 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
SalesReportuses the protectedtitle(via the inheritedheader()) and overrides the protectedbody()method.- Outside code can only call
render(); it cannot callheader()orbody()directly. salesis private toSalesReport; even the parentReportcannot 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
| Member | Without a Modifier |
|---|---|
| Methods | public |
| Constants | public |
| Properties | A 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.
| Situation | Visibility |
|---|---|
| Part of the class's purpose, used by other code | public |
| An extension point that child classes should override or use | protected |
| Internal state and helper methods | private |
| Value others may read but must not change | public 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; useprotectedfor deliberate extension points; usepublicfor the class's intended API. - Prefer
public readonlyover 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