Tools
Log in
English

Learn to codePHP

PHP access modifiers

Based on PHP 8.3

PHP public, protected and private on shop coupons, plus readonly and 8.4.

In one line

Access modifiers sort properties, methods and constants by who may see them. PHP has three: public (everyone), protected (the class and its children) and private (the class only). A method with no keyword is public.

Why you need it

If the rate and secret of a coupon are all public, order page code can set the rate to 90 and nothing stops it. Tracking down the line that did it takes ages.

Split what the world may see (code, apply()), what only children may touch (percent) and what the class keeps to itself (secret), and the blast radius of every change is known in advance. private names can be renamed without fear.

Everyday picture

Picture a shop. The shelves (public) are open to every customer, the stockroom (protected) to staff of the main store and its franchises, and the safe in the office (private) only to people of that one shop. Just as shop staff can open any safe in their own shop, PHP private lets code of a class open that slot on any object of the class.

Example code

main.php · 54 lines
<?phpdeclare(strict_types=1); class Coupon{    public const PREFIX = 'APP';    protected int $percent;    private string $secret;     public function __construct(public readonly string $code, int $percent)    {        $this->percent = $percent;        $this->secret = strrev($code);    }     public function apply(int $price): int    {        return $price - intdiv($price * $this->percent, 100);    }     public function sameSecret(Coupon $other): bool    {        return $this->secret === $other->secret;    }} class VipCoupon extends Coupon{    public function apply(int $price): int    {        $this->percent += 5;        $price = parent::apply($price);        $this->percent -= 5;        return $price;    }     public function peek(): string    {        return isset($this->secret) ? 'can see' : 'cannot see';    }} $c = new Coupon('SPRING10', 10);$v = new VipCoupon('SPRING10', 10);echo Coupon::PREFIX . '-' . $c->code, "\n";echo $c->apply(20000), ' / ', $v->apply(20000), "\n";var_dump($c->sameSecret($v));echo $v->peek(), "\n";$kinds = [];foreach (['code', 'percent', 'secret'] as $name) {    $r = new ReflectionProperty(Coupon::class, $name);    $kinds[] = $name . '=' . ($r->isPublic() ? 'public' : ($r->isProtected() ? 'protected' : 'private'));}echo implode(' ', $kinds), "\n";

PHP visibility at a glance

Same classChild classOutside codeAnother object of the same class
publicOOOO
protectedOOXO
privateOXXO

readonly is a separate flag on top of visibility: once set, the value cannot change (since 8.1). PHP 8.4 adds public private(set) to give reading and writing different scopes (new in 8.4). A method with no keyword is public.

When to use it

  • Start with everything private and open things one step at a time when needed
  • Use protected only for values children truly must change
  • For read-only access from outside, consider public readonly (8.1) or public private(set) in 8.4

PHP has no package-level visibility like Java. A namespace only groups names; it does not limit who can see them.

Common mistakes

Reading a parent private property in a child

To child code, a parent private slot simply does not exist. PHP does not stop; it warns and hands back null, so the bug surfaces late. If children need the value, make it protected.

Wrong

class Coupon{    private string $secret = 'abc';} class VipCoupon extends Coupon{    public function show(): ?string    {        return $this->secret;    }} echo (new VipCoupon())->show() ?? 'nothing', "\n";

When you run itWarning: Undefined property: VipCoupon::$secret nothing

Fixed

class Coupon{    protected string $secret = 'abc';} class VipCoupon extends Coupon{    public function show(): ?string    {        return $this->secret;    }} echo (new VipCoupon())->show() ?? 'nothing', "\n";

When you run itabc

Narrowing public to protected in an override

A child must be callable wherever the parent is. Outside code calls $coupon->apply(), so a child that blocks it would break things, and PHP refuses the class when loading it.

Wrong

class Coupon{    public function apply(int $price): int    {        return $price;    }} class VipCoupon extends Coupon{    protected function apply(int $price): int    {        return $price - 1000;    }}

What PHP saysFatal error: Access level to VipCoupon::apply() must be public (as in class Coupon)

Fixed

class Coupon{    public function apply(int $price): int    {        return $price;    }} class VipCoupon extends Coupon{    public function apply(int $price): int    {        return $price - 1000;    }} echo (new VipCoupon())->apply(5000), "\n";

When you run it4000

Changing a readonly value inside the class

readonly is not only for outsiders; even the class itself may set it only once. When you need a changed value, return a new object from a with...() method.

Wrong

final class Code{    public function __construct(public readonly string $value)    {    }     public function rename(string $v): void    {        $this->value = $v;    }} (new Code('A1'))->rename('B2');

When you run itFatal error: Uncaught Error: Cannot modify readonly property Code::$value

Fixed

final class Code{    public function __construct(public readonly string $value)    {    }     public function withValue(string $v): static    {        return new static($v);    }} $a = new Code('A1');$b = $a->withValue('B2');echo $a->value, ' ', $b->value, "\n";

When you run itA1 B2

Check yourself

Question 1

With the example Coupon, what does echo $x->percent; from outside do?

Show the answer

Answer: 2. It throws an `Error` protected is open only to code in the class and its children. Reading it from outside throws an Error.

Question 2

Two coupons with the same code compare secrets. What prints?

var_dump((new Coupon('Q', 1))->sameSecret(new Coupon('Q', 99)));

Show the answer

Answer: 1. bool(true) sameSecret() is Coupon code, so it may read the private slot of another coupon. The secret is the reversed code, 'Q' for both.

Questions people ask

Can private code see another object of the same class?

Yes. PHP private means code of that class, so its methods can read private properties of any object of the class.

What happens when a child reads a parent private property?

The child sees no such property, so PHP warns and returns null. Make it protected if children need it.

What is a method with no keyword?

public. PSR-12 asks you to write public anyway so the code reads clearly.