CodeBlanks Logo Icon CodeBlanks

protected access

PHP course · Intermediate · Lesson 25/115

Learn that protected access is limited to the class and its subclasses.

protected access, in the visibility context

You saw the protected modifier briefly in the inheritance lesson. Now let's look at it more closely in the visibility context.

When a property or method is protected, it can only be accessed from:

  • inside the class that declares it
  • subclasses that extends this class
  • parent classes in the same hierarchy

Direct access from outside is not possible: writing $obj->protectedProp triggers a fatal error. So protected is ideal for data you want to hide from the outside but expose to subclasses.

protected cannot be reached from outside

Consider this example: class Animal { protected string $name; }. Here $name is protected. From outside the class, writing $cat->name triggers a fatal error: Cannot access protected property.

But if you write Dog extends Animal and inside Dog you access $this->name, it works. Because Dog is a subclass of Animal, it can use protected members.

In other words, protected is closed to the outside world but open to subclasses through inheritance. This lets subclasses reuse the parent's internal state.

Exercise Subclass with a protected property

Define an Animal class with a protected string $name property and a __construct(string $name) that assigns $this->name = $name. Then declare Dog extends Animal with a public function getName(): string method that does return $this->name. Finally create $dog = new Dog("Buddy") and print echo $dog->getName() . "\n".

Show example solution
Declare protected $name in Animal, Dog extends Animal, getName returns $this->name.
Example solution:
<?php
// Define Animal and Dog classes
class Animal {
    protected string $name;
    public function __construct(string $name) {
        $this->name = $name;
    }
}
class Dog extends Animal {
    public function getName(): string {
        return $this->name;
    }
}
$dog = new Dog("Buddy");
echo $dog->getName() . "\n";

Test yourself

  1. From where can a protected property be accessed?

    • From inside the declaring class and its subclasses
    • Only from inside the declaring class
    • From anywhere outside the class
    • Only at file level, from outside the class
    Show answer

    From inside the declaring class and its subclasses — Correct. protected members are reachable from the class and its subclasses.

  2. Declare a protected property

    class Animal {
        ____
    }
    Show answer
    class Animal {
        protected $name;
    }
  3. Match the protected expressions

    protected property
    Class and subclasses
    Outside access
    Triggers fatal error
    Inheritance with extends
    Grants protected access
    Parent $this->name
    In-class access

All lessons in Intermediate