PHP Access Modifiers

PHP Access Modifiers

Access modifiers control the visibility of class properties and methods — a core pillar of encapsulation.

1 - The Three Levels

  • public — accessible from anywhere
  • protected — accessible within the class and its subclasses
  • private — accessible only within the declaring class

2 - Example

class BankAccount {
    public string $owner;
    protected float $balance;
    private string $pin;

    public function __construct(string $owner, float $balance, string $pin) {
        $this->owner   = $owner;
        $this->balance = $balance;
        $this->pin     = $pin;
    }

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

    private function verifyPin(string $pin): bool {
        return hash_equals($this->pin, $pin);
    }

    public function withdraw(float $amount, string $pin): string {
        if (!$this->verifyPin($pin)) return "Invalid PIN";
        if ($amount > $this->balance) return "Insufficient funds";
        $this->balance -= $amount;
        return "Withdrew $$amount";
    }
}

3 - Getters and Setters

class Product {
    private float $price = 0;

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

    public function setPrice(float $price): void {
        if ($price < 0) {
            throw new InvalidArgumentException("Price cannot be negative");
        }
        $this->price = $price;
    }
}

4 - readonly (PHP 8.1)

class Point {
    public function __construct(
        public readonly float $x,
        public readonly float $y
    ) {}
}

$p = new Point(3.0, 4.0);
echo $p->x;   // 3.0
// $p->x = 5; // Error: Cannot modify readonly property

Note: Favour private for properties by default. This enforces encapsulation — callers can only interact with controlled public or protected methods.

-Tip-