PHP Access Modifiers
Access modifiers control who can access properties and methods. They're essential for encapsulation - hiding internal details and exposing only what's necessary!
Output
Click Run to execute your code
Three Access Levels
| Modifier | Class | Subclass | Outside |
|---|---|---|---|
public |
✅ | ✅ | ✅ |
protected |
✅ | ✅ | ❌ |
private |
✅ | ❌ | ❌ |
Public - Accessible Everywhere
<?php
class User {
public $name; // Accessible anywhere
}
$user = new User();
$user->name = "Alice"; // OK
?>
Protected - Class and Subclasses
<?php
class User {
protected $email; // Only in class and subclasses
}
// $user->email = "..."; // Error!
?>
Private - Class Only
<?php
class BankAccount {
private $pin; // Only within this class
public function validatePin($pin) {
return $this->pin === $pin;
}
}
?>
Summary
- public: Accessible everywhere
- protected: Class + subclasses only
- private: Class only
- Encapsulation: Hide internal details
What's Next?
Next, learn about Inheritance - reusing code with the extends keyword!
Enjoying these tutorials?