TExcelTAD
Home › PHP › PHP Access Modifiers

PHP Access Modifiers

Access modifiers (also called visibility keywords) control which code is allowed to read or call a property, method or constant. They are the main tool for encapsulation: keeping an object's internals private so it can protect its own rules.

The three visibilities

Modifier Accessible from the class itself From child classes From outside
public yes yes yes
protected yes yes no
private yes no no

If you leave the modifier off a method, it is public. Properties must always be declared with a modifier (or var, an old synonym for public).

php · try it yourself
<?php
class Account {
    public string $owner;
    protected string $type = 'basic';
    private float $balance = 0;

    public function __construct(string $owner) {
        $this->owner = $owner;
    }

    public function deposit(float $amount): void {
        $this->balance += $amount;
    }

    public function balance(): float {
        return $this->balance;
    }
}

$acc = new Account('Lan');
$acc->deposit(50);
echo "{$acc->owner} has {$acc->balance()}\n";

try {
    $acc->balance = 1000000;
} catch (Error $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

try {
    echo $acc->type;
} catch (Error $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
Lan has 50
Error: Cannot access private property Account::$balance
Error: Cannot access protected property Account::$type

Outside code can only change the balance through deposit(), which is where you would add rules such as "amount must be positive".

Private methods

Methods can be private too. That is ideal for helper steps that make sense only inside the class:

php · try it yourself
<?php
class PasswordPolicy {
    public function check(string $password): string {
        if (!$this->longEnough($password)) {
            return 'too short';
        }
        if (!$this->hasDigit($password)) {
            return 'needs a digit';
        }
        return 'ok';
    }

    private function longEnough(string $p): bool {
        return strlen($p) >= 8;
    }

    private function hasDigit(string $p): bool {
        return preg_match('/\d/', $p) === 1;
    }
}

$policy = new PasswordPolicy();
foreach (['abc', 'abcdefgh', 'abcdefg1'] as $pw) {
    echo str_pad($pw, 10) . $policy->check($pw) . "\n";
}

try {
    $policy->hasDigit('x1');
} catch (Error $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
abc       too short
abcdefgh  needs a digit
abcdefg1  ok
Error: Call to private method PasswordPolicy::hasDigit() from global scope

Because the helpers are private, you can rename or rewrite them later without breaking any code outside the class.

protected vs private with inheritance

A child class (see the next lessons on inheritance) can use protected members of its parent, but not private ones:

php · try it yourself
<?php
class Vehicle {
    protected int $wheels = 4;
    private string $vin = 'X123';
}

class Bike extends Vehicle {
    public function info(): string {
        $this->wheels = 2;              // protected: allowed
        return "wheels: {$this->wheels}";
    }

    public function vin(): string {
        return $this->vin ?? 'not visible here';
    }
}

$bike = new Bike();
echo $bike->info() . "\n";
echo $bike->vin() . "\n";
wheels: 2
not visible here

Inside Bike, $this->vin does not see the parent's private property at all — it behaves like an undefined property, so ?? falls back to the default text.

Asymmetric visibility (PHP 8.4)

A common pattern is "everyone may read this property, but only the class may change it". Before PHP 8.4 you needed a private property plus a getter method. PHP 8.4 lets you give reading and writing different visibilities:

php · try it yourself
<?php
class Order {
    public private(set) string $status = 'new';

    public function ship(): void {
        $this->status = 'shipped';
    }
}

$o = new Order();
echo "Status: {$o->status}\n";
$o->ship();
echo "Status: {$o->status}\n";

try {
    $o->status = 'cancelled';
} catch (Error $e) {
    echo "Error: " . $e->getMessage() . "\n";
}
Status: new
Status: shipped
Error: Cannot modify private(set) property Order::$status from global scope

public private(set) means: public read, private write. You can also use protected(set) to let child classes write. PHP 8.4 also added property hooks (get / set blocks attached to a property), which are another way to control access without writing separate getter and setter methods.

Tip: Start with private and only widen the visibility when you have a reason. It is easy to make something public later, but hard to take public access away once other code depends on it.

Test yourself

Which visibility allows access from the class and its subclasses, but not from outside?

  1. public
  2. protected
  3. private
  4. static

What is the default visibility of a method declared without a modifier?

  1. private
  2. protected
  3. public
  4. It is a syntax error

What does public private(set) int $count; mean in PHP 8.4?

  1. The property is private everywhere
  2. Anyone can read it, only the class can write it
  3. Anyone can write it, only the class can read it
  4. It is a static property