public, protected, and privatePHP access modifiers—public, protected, and private—control which parts of your codebase can read or call a class's properties, methods, and constants. Encapsulating internal state behind clear visibility boundaries prevents outside code from breaking object invariants.
Choose the strictest visibility level that still lets collaborators use your class cleanly.
| Modifier | Inside Same Class | Inside Child Classes | Outside the Class |
|---|---|---|---|
public |
Yes | Yes | Yes |
protected |
Yes | Yes | No |
private |
Yes | No | No |
<?php
declare(strict_types=1);
class Order
{
private array $items = [];
protected float $taxRate = 0.08;
public function addItem(string $name, float $price): void
{
if ($price < 0) {
throw new InvalidArgumentException('Price cannot be negative.');
}
$this->items[] = ['name' => $name, 'price' => $price];
}
public function calculateTotal(): float
{
$subtotal = array_sum(array_column($this->items, 'price'));
return round($subtotal * (1 + $this->taxRate), 2);
}
}
$order = new Order();
$order->addItem('USB Hub', 30.00);
echo "Total with tax: $" . $order->calculateTotal() . PHP_EOL;
Because $items is private, external callers must go through addItem(), which guarantees negative prices can never sneak into the order total.
readonlyIn PHP 8.1+, marking a property public readonly string $id lets outside code read $order->id directly without writing a boilerplate getId() getter, while still blocking external reassignments.
public out of habit: Mutable public properties let any caller bypass validation checks. Default to private or public readonly.public when only used internally: Internal formatting or parsing helpers belong in private methods so you can refactor them freely later without breaking callers.public/private defaults a method to public, though PSR-12 coding standards require declaring visibility explicitly on every method and property.private properties?Yes. In PHP, visibility is enforced at the class level, not the object instance level—so $this->compare($otherOrder) can read $otherOrder->items.
protected instead of private?Use protected only when a property or hook method is intentionally designed to be overridden or read by subclasses. Otherwise, prefer private.
Yes. Since PHP 7.1, class constants support public const, protected const, and private const.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.