← Back to PHP Course | Chapter 8: OOP | Lesson 4 of 14

PHP Access Modifiers

Introduction to Access Modifiers

public, protected, and private control which code is allowed to read or modify a property or call a method, letting a class expose a clean interface while hiding its internal implementation details.

Example: Introduction to Access Modifiers

php
<?php
class BankAccount {
    private $balance = 100;
    public function getBalance() {
        return $this->balance;
    }
}
$account = new BankAccount();
echo $account->getBalance();
?>

The Public Modifier

public members are accessible from anywhere, including outside the class entirely, and are the default visibility PHP uses if you omit a modifier — though explicitly stating it is considered better practice.

Example: The Public Modifier

php
<?php
class Car {
    public $color = "red";
}
$car = new Car();
echo $car->color;
?>

The Private Modifier

private members are accessible only from within the exact class that defines them, not even from a subclass, which is how you truly hide internal state that no other code (including child classes) should touch directly.

Example: The Private Modifier

php
<?php
class Account {
    private $pin = "1234";
    function checkPin($input) {
        return $input === $this->pin;
    }
}
$account = new Account();
var_dump($account->checkPin("1234"));
?>

The Protected Modifier

protected members sit in between: accessible from the defining class and any class that extends it, but not from outside code, which is the right choice for internal details a subclass legitimately needs to build on.

Example: The Protected Modifier

php
<?php
class Animal {
    protected $sound = "...";
}
class Dog extends Animal {
    function makeSound() {
        echo $this->sound;
    }
}
$dog = new Dog();
$dog->makeSound();
?>

Getter and Setter Methods

Restricting properties to private or protected and exposing controlled access through public methods (getters/setters) is a core encapsulation technique that prevents external code from putting an object into an invalid state.

Example: Getter and Setter Methods

php
<?php
class Account {
    private $balance = 0;
    function setBalance($amount) {
        if ($amount >= 0) {
            $this->balance = $amount;
        }
    }
    function getBalance() {
        return $this->balance;
    }
}
$account = new Account();
$account->setBalance(500);
echo $account->getBalance();
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.