PHP Access Modifiers
Learn about access modifiers in PHP and how they control the visibility of class properties and methods.
Introduction to Access Modifiers
Access modifiers are keywords used to define the accessibility of class members (properties and methods). PHP supports three types of access modifiers: public, protected, and private.
Types of Access Modifiers
- Public: Members declared as public can be accessed from anywhere, both inside and outside the class.
- Protected: Members declared as protected can only be accessed within the class itself and by inheriting (child) classes.
- Private: Members declared as private can only be accessed within the class itself. They are not accessible in child classes.
Using Public Access Modifier
Public properties and methods are accessible from any context. Here’s an example:
<?php
class Dog {
public $name;
public function bark() {
echo "Woof! My name is {$this->name}.
";
}
}
$dog = new Dog();
$dog->name = "Rex"; // Accessing public property
$dog->bark(); // Calling public method
?>
Using Protected Access Modifier
Protected properties and methods can be accessed within the class and by subclasses. Here’s an example:
<?php
class Animal {
protected $species;
public function setSpecies($species) {
$this->species = $species; // Accessing protected property
}
}
class Cat extends Animal {
public function getSpecies() {
return $this->species; // Accessing protected property from the parent class
}
}
$cat = new Cat();
$cat->setSpecies("Feline");
echo $cat->getSpecies(); // Outputs: Feline
?>
Using Private Access Modifier
Private properties and methods can only be accessed within the class itself. They are not accessible in child classes. Here’s an example:
<?php
class BankAccount {
private $balance;
public function __construct($initialBalance) {
$this->balance = $initialBalance; // Accessing private property
}
public function deposit($amount) {
$this->balance += $amount; // Accessing private property
}
public function getBalance() {
return $this->balance; // Accessing private property
}
}
$account = new BankAccount(100);
$account->deposit(50);
echo $account->getBalance(); // Outputs: 150
// $account->balance; // Error: Cannot access private property
?>
Conclusion
Access modifiers are essential in PHP for encapsulation, allowing developers to control the visibility of class members. Using public, protected, and private modifiers helps protect the internal state of an object and maintain a clean interface.