Visibility

Visibility and encapsulation: public/protected/private in real code.

On this page

Visibility Overview

Visibility controls what can access a property/method. Use it to protect internal state and enforce rules through methods rather than direct access.

public

public members are accessible from anywhere. Keep public surface small and intentional.

<?php
class PublicExample {
  public string $name = "Ozan";
}

$x = new PublicExample();
echo $x->name;

private

private members are accessible only inside the class. This is the most common choice for internal state.

<?php
class BankAccount {
  private int $balance = 0;

  public function deposit(int $amount): void {
    if ($amount <= 0) {
      throw new Exception("Invalid amount");
    }
    $this->balance += $amount;
  }

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

protected

protected members are accessible in the class and its subclasses. Use it when inheritance is truly needed (often composition is better).

<?php
class BaseService {
  protected function now(): string {
    return date("c");
  }
}

class ReportService extends BaseService {
  public function build(): string {
    return "Generated at: " . $this->now();
  }
}

Encapsulation in Practice

Encapsulation means consumers cannot break your rules by mutating internal state directly. Expose safe methods and keep the rest private.

Production Tip

Default to private. Promote to public only when you are sure it should be part of the class API. A small public API is easier to maintain.