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
PHP OOP Introduction
PHP Class
PHP Objects
Exercises & Assignments
No Content Found.
Interview Questions & Answers
How to create a class and object in PHP?
What is the difference between public, private and protected in PHP?
Is multiple inheritance supported in PHP?
What is the meaning of final class and final method in PHP?
What is the difference between abstract class and interface in PHP?
What are traits in PHP?
What is a constructor in PHP?