Access modifiers control the visibility of class properties and methods — a core pillar of encapsulation.
public — accessible from anywhereprotected — accessible within the class and its subclassesprivate — accessible only within the declaring classclass 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";
}
}
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;
}
}
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