Cannot Access Protected Property

Fatal error: Uncaught Error: Cannot access protected property App\Entity\User::$password

Quick Answer

You are trying to access a protected property from outside the class hierarchy. Use a public getter method or change the visibility.

Why This Happens

Protected properties are only accessible within the class and its subclasses. External code cannot read or write them directly. This encapsulation is intentional. Use public getter and setter methods to provide controlled access to protected properties.

The Problem

class User {
    protected string $password;

    public function __construct(string $password) {
        $this->password = password_hash($password, PASSWORD_DEFAULT);
    }
}
$user = new User('secret');
echo $user->password; // Cannot access protected property

The Fix

class User {
    protected string $password;

    public function __construct(string $password) {
        $this->password = password_hash($password, PASSWORD_DEFAULT);
    }

    public function verifyPassword(string $password): bool {
        return password_verify($password, $this->password);
    }
}
$user = new User('secret');
if ($user->verifyPassword('secret')) {
    echo 'Authenticated';
}

Step-by-Step Fix

  1. 1

    Understand the visibility

    The property is protected intentionally. Determine if you should access it directly or through a method.

  2. 2

    Use a getter method

    Create a public method that provides controlled access to the property value.

  3. 3

    Change visibility if needed

    If the property genuinely needs to be publicly accessible, change protected to public. But prefer methods for encapsulation.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free