Access Modifiers
Control where properties and methods can be accessed with public, protected and private.
Syntax
private $balance;Access modifiers set the visibility of properties and methods:
public— accessible from anywhere.protected— accessible within the class and its subclasses.private— accessible only within the class itself.
Keeping data private and exposing it through methods is called encapsulation.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Mark a User's password property as private so it can only be set through a validated setPassword() method.
- Use protected on a base class's database connection so subclasses can access it but external code cannot.
- Expose only a public getBalance() method on a BankAccount while keeping the $balance property private.
More examples
public, protected and private
private hides balance from external code; the only way to modify it is through the controlled deposit() method.
<?php
class BankAccount {
private float $balance = 0;
public function deposit(float $amount): void {
if ($amount > 0) {
$this->balance += $amount;
}
}
public function getBalance(): float {
return $this->balance;
}
}
$acct = new BankAccount();
$acct->deposit(100);
echo $acct->getBalance(); // 100
// $acct->balance; // Fatal: private propertyProtected in inheritance
protected allows the $db connection to be used by child classes but keeps it hidden from the rest of the application.
<?php
class BaseRepo {
protected \PDO $db;
public function __construct(\PDO $db) {
$this->db = $db;
}
}
class UserRepo extends BaseRepo {
public function findAll(): array {
return $this->db->query('SELECT * FROM users')->fetchAll();
}
}
Getters and setters pattern
Encapsulating $celsius behind a setter lets the class enforce the absolute-zero invariant on every assignment.
<?php
class Temperature {
private float $celsius;
public function __construct(float $celsius) {
$this->setCelsius($celsius);
}
public function setCelsius(float $c): void {
if ($c < -273.15) throw new \RangeException('Below absolute zero');
$this->celsius = $c;
}
public function getFahrenheit(): float {
return $this->celsius * 9 / 5 + 32;
}
}
$t = new Temperature(100);
echo $t->getFahrenheit(); // 212
Discussion