PHP Public vs Protected vs Private Visibility Modifiers

In PHP object-oriented programming, visibility modifiers (also known as access modifiers) define where class properties and methods can be accessed. This article provides a direct comparison of the three primary visibility modifiers—public, protected, and private—explaining their rules, inheritance behavior, and practical use cases to help you write secure and well-structured code.

Public Visibility

The public modifier is the least restrictive access level in PHP.

class User {
    public $username = "JohnDoe";

    public function getUsername() {
        return $this->username;
    }
}

$user = new User();
echo $user->username; // Works: accessed from outside the class

Protected Visibility

The protected modifier restricts access to the defining class and its descendants.

class ParentClass {
    protected $apiKey = "secret_123";
}

class ChildClass extends ParentClass {
    public function showKey() {
        return $this->apiKey; // Works: child class can access protected parent property
    }
}

$child = new ChildClass();
// echo $child->apiKey; // Error: Cannot access protected property
echo $child->showKey(); // Works

Private Visibility

The private modifier is the most restrictive access level.

class Database {
    private $connectionString = "mysql://host";

    private function connect() {
        // Internal connection logic
    }
}

class MySQLDatabase extends Database {
    public function testConnection() {
        // return $this->connectionString; // Error: Cannot access private property of parent
    }
}

Quick Reference Summary

Modifier Access from inside the same class? Access from inheriting child classes? Access from outside the class?
public Yes Yes Yes
protected Yes Yes No
private Yes No No