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.

KeywordCan be accessed from
publicAnywhere: inside the class, in child classes and outside the class
protectedInside the class and in its child classes only
privateInside 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.