Access modifiers are keywords that define the **visibility** of class properties and methods. They control where a specific property or method can be accessed from, which is a core part of a concept called **Encapsulation**.
PHP provides three main keywords to control access:
| Modifier | Description |
|---|---|
public |
The property or method can be accessed from anywhere (default). |
protected |
Can only be accessed within the class itself and by derived (child) classes. |
private |
Can only be accessed within the class itself. |
Properties and methods declared as public are accessible from outside the class. If you don't specify a modifier, PHP treats them as public by default.
<?php
class Fruit {
public $name; // Public property
}
$apple = new Fruit();
$apple->name = "Apple"; // OK: can be accessed from outside
?>
The protected modifier restricts access to the class itself and any class that **inherits** (extends) it. You cannot access it from outside these classes.
<?php
class Fruit {
protected $name;
}
$apple = new Fruit();
$apple->name = "Apple"; // Error: Cannot access protected property
?>
protected when you want to allow child classes to use a property while keeping it hidden from the rest of the application.
The private modifier is the most restrictive. A private property or method can only be accessed within the specific class where it is defined. Not even child classes can access it.
<?php
class Fruit {
private $name;
}
$apple = new Fruit();
$apple->name = "Apple"; // Error: Cannot access private property
?>
| Access From | Public | Protected | Private |
|---|---|---|---|
| Same Class | Yes | Yes | Yes |
| Child Class | Yes | Yes | No |
| Outside Class | Yes | No | No |
private or protected and provide public methods (getters and setters) to interact with them.
Now that you know how to control access, let's explore how one class can inherit properties and methods from another in the **PHP Inheritance** lesson.