๐ŸŽ“ A1Learner
๐Ÿ”

PHP Access Modifiers

Access modifiers control where a property or method can be reached from. PHP has three modifiers named public, private, and protected.

A private property read through a method

The balance stays private. A public method reads it from inside the class.

<?php
class Account {
  private $balance = 150;
  public function getBalance() {
    return $this->balance;
  }
}
$account = new Account();
echo $account->getBalance(), "\n";

A protected property read by a child class

The child class reads the protected brand through its own method.

<?php
class Vehicle {
  protected $brand = "Ford";
}
class Car extends Vehicle {
  public function getBrand() {
    return $this->brand;
  }
}
$car = new Car();
echo $car->getBrand(), "\n";

Reading a private property from outside

Code outside the class tries to read the private property directly.

<?php
class Account {
  private $balance = 150;
}
$account = new Account();
echo $account->balance, "\n";

Example

<?php
class Vault {
  private $code;
  public function __construct($code) {
    $this->code = $code;
  }
  public function getCode() {
    return $this->code;
  }
}
$vault = new Vault("4815");
echo $vault->getCode(), "\n";

Key points

  • Public members can be reached from anywhere.
  • Private members can be reached only inside their own class.
  • Protected members can be reached inside their class and inside child classes.
  • A public method can read a private property for code outside the class.
  • Access modifiers set how far a member can be reached.

In this example, the Vault class stores its code in a private property. The constructor saves the code given at creation. The getCode method reads the code from inside the class. The last line prints the code through that method.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz PHP Compiler

Exercise

Code outside a class tries to read a private property directly. What happens?