PHP Access Modifiers
In this page:
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
class BankAccount {
private $balance = 100;
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount();
echo $account->getBalance();
?>
Login to try C/C++/Java/PHP code in the editor
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
class Car {
public $color = "red";
}
$car = new Car();
echo $car->color;
?>
Login to try C/C++/Java/PHP code in the editor
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
class Account {
private $pin = "1234";
function checkPin($input) {
return $input === $this->pin;
}
}
$account = new Account();
var_dump($account->checkPin("1234"));
?>
Login to try C/C++/Java/PHP code in the editor
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
class Animal {
protected $sound = "...";
}
class Dog extends Animal {
function makeSound() {
echo $this->sound;
}
}
$dog = new Dog();
$dog->makeSound();
?>
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: