Question
In PHP classes, what is the difference between public, private, and protected methods and properties? When should each one be used, and why?
Examples:
// Public
public $variable;
public function doSomething() {
// ...
}
// Private
private $variable;
private function doSomething() {
// ...
}
// Protected
protected $variable;
protected function doSomething() {
// ...
}
Short Answer
By the end of this page, you will understand how visibility works in PHP classes, what public, private, and protected mean, and how to choose the right one for properties and methods. You will also see practical examples, common mistakes, and how these access levels are used in real projects.
Concept
In PHP, public, private, and protected are visibility keywords. They control where a property or method can be accessed from.
Visibility matters because classes are meant to hide internal details and expose only the parts that other code should use. This helps you:
- protect important data from accidental changes
- keep class internals flexible
- make your code easier to understand and maintain
- enforce clear boundaries between a class and the outside world
Here is the core idea:
public: accessible from anywhereprivate: accessible only inside the same classprotected: accessible inside the same class and its child classes
Why this matters
Imagine a class represents a bank account. You probably want other code to call a method like deposit() or withdraw(), but you do not want external code directly changing the balance in unsafe ways.
That is why visibility is useful: it lets you define a safe public interface and hide the internal implementation.
Quick definition
public
Use public for methods and properties that are intended to be used by other parts of your program.
Mental Model
Think of a class like a building.
publicis the front door: anyone is allowed in.protectedis the staff-only area: the building's workers and approved branches can enter.privateis the owner's locked office: only that exact office owner can access it.
Another way to think about it:
public= what the class promises to the outside worldprivate= how the class works internallyprotected= internal tools that subclasses are allowed to reuse
This mental model helps with design:
- If outside code should use it directly, make it
public. - If it is an implementation detail, make it
private. - If subclasses need it but outside code should not, make it
protected.
Syntax and Examples
Basic syntax
class Example {
public string $publicProperty = 'visible everywhere';
protected string $protectedProperty = 'visible in class and subclasses';
private string $privateProperty = 'visible only in this class';
public function publicMethod(): void {
echo "Public method\n";
}
protected function protectedMethod(): void {
echo "Protected method\n";
}
private function privateMethod(): void {
echo "Private method\n";
}
}
Example: safe class design
class {
= ;
{
( > ) {
->balance += ;
}
}
{
->balance;
}
}
= ();
->();
->();
Step by Step Execution
Consider this example:
class Counter {
private int $count = 0;
public function increment(): void {
$this->count++;
}
public function getCount(): int {
return $this->count;
}
}
$counter = new Counter();
$counter->increment();
$counter->increment();
echo $counter->getCount();
Step by step
1. The class is defined
Counter has:
- a private property
$count - a public method
increment() - a public method
Real World Use Cases
1. Protecting data in domain objects
In an e-commerce app, an Order class may store internal state such as total price, status, or discount calculations.
class Order {
private float $total = 0;
public function addItem(float $price): void {
$this->total += $price;
}
public function getTotal(): float {
return $this->total;
}
}
This prevents outside code from doing something unsafe like:
// Not allowed if $total is private
$order->total = -500;
2. Creating a clean public API
Libraries often expose only a few public methods and keep helper logic private.
Real Codebase Usage
In real projects, visibility is used to separate a class into two parts:
- public API: what other code is allowed to call
- internal implementation: helper methods and internal state
Common patterns
Guarding internal state
Developers often make properties private and expose public getter/setter methods only when needed.
class Product {
private float $price;
public function setPrice(float $price): void {
if ($price < 0) {
throw new InvalidArgumentException('Price cannot be negative');
}
$this->price = $price;
}
public function getPrice(): float {
return $this->price;
}
}
Common Mistakes
1. Making everything public
Beginners often mark all properties and methods as public.
class User {
public string $email;
public string $password;
}
Why this is a problem
- outside code can change anything at any time
- validation becomes harder
- internal structure becomes part of the public contract
Better approach
class User {
private string $email;
private string $password;
public function setEmail(string $email): void {
$this->email = $email;
}
public function getEmail(): {
->email;
}
}
Comparisons
Visibility comparison
| Keyword | Accessible inside same class | Accessible in child classes | Accessible from outside | Typical use |
|---|---|---|---|---|
public | Yes | Yes | Yes | Class API |
protected | Yes | Yes | No | Shared internals for inheritance |
private | Yes | No | No | Internal implementation details |
private vs protected
Cheat Sheet
Quick rules
public= accessible everywhereprotected= accessible in the class and subclassesprivate= accessible only in the same class
Access table
| From where? | public | protected | private |
|---|---|---|---|
| Same class | Yes | Yes | Yes |
| Child class | Yes | Yes | No |
| Outside object usage | Yes | No | No |
Syntax
class Example {
public $a;
protected ;
;
{}
{}
{}
}
FAQ
What does public mean in PHP?
public means a property or method can be accessed from anywhere: inside the class, from child classes, and from outside objects.
What does private mean in PHP?
private means only the same class can access that property or method directly.
What does protected mean in PHP?
protected means the current class and its child classes can access it, but outside code cannot.
Should class properties be private in PHP?
Usually, yes. Making properties private helps protect data and lets you control access through methods.
Can a child class access private properties in PHP?
No. A child class cannot directly access a parent's private properties or methods.
When should I use protected instead of private?
Use protected when subclasses genuinely need access to a property or method. Otherwise, prefer private.
Is it bad to make everything public?
In most cases, yes. It exposes internal details, makes validation harder, and increases coupling between parts of your code.
Can protected members be accessed outside the class?
Mini Project
Description
Build a simple BankAccount class to practice choosing the right visibility for properties and methods. This project demonstrates how to protect internal data, expose safe public methods, and optionally use a protected helper for subclasses.
Goal
Create a PHP class that allows deposits and withdrawals through public methods while keeping the balance protected from direct external modification.
Requirements
- Create a
BankAccountclass with a balance that cannot be accessed directly from outside the class. - Add public methods to deposit money, withdraw money, and read the current balance.
- Prevent invalid deposits or withdrawals, such as negative amounts or withdrawing more than the balance.
- Add one internal helper method for validation.
- Show the class being used with a few example operations.
Keep learning
Related questions
Converting HTML and CSS to PDF in PHP: Core Concepts, Limits, and Practical Approaches
Learn how HTML-to-PDF conversion works in PHP, why CSS support varies, and how to choose practical approaches for reliable PDF output.
How PHP foreach Actually Works with Arrays
Learn how PHP foreach works internally, including array copies, internal pointers, by-value vs by-reference behavior, and common pitfalls.
How to Check String Prefixes and Suffixes in PHP
Learn how to check whether a string starts or ends with specific text in PHP using simple functions and practical examples.