What is the difference between public, private and protected in PHP?
public, protected and private are access modifiers (also called visibility). They decide who can use a property or a method of a class.
| Keyword | Can be accessed from |
|---|---|
| public | Anywhere: inside the class, in child classes and outside the class |
| protected | Inside the class and in its child classes only |
| private | Inside the same class only |
<?php
class Account {
public $name = "Robin";
protected $type = "Savings";
private $pin = 1234;
}
$acc = new Account();
echo $acc->name; // works, it is public
// echo $acc->pin; // Fatal error, private property can not be accessed outside
?>
Output:
Tutorials Class - Output Window
Robin
If you try to read a private or protected property from outside the class, PHP stops with a fatal error. To give controlled access, we normally write public methods (getters and setters) inside the class.
Note:
The words transient and volatile are from Java, they do not exist in PHP.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |